Sick Gaming
[Tut] How I Built an OpenAI-Powered Web Assistant with Django - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.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

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1205499&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</p></div>
<p>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.</p>
<h2>Set Up</h2>
<p>To get started, we will create a directory where every file will live in. In the directory, we will create and activate a <a href="https://blog.finxter.com/python-virtual-environments-with-venv-a-step-by-step-guide/" data-type="post" data-id="3393" target="_blank" rel="noreferrer noopener">virtual environment</a>. 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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir project &amp;&amp; cd project
python3 -m venv .venv
source .venv/bin/activate</pre>
<p>In the project directory, we create and activate a virtual environment using the <code>source</code> command. You can also replace the <code>source</code> command with a dot <code>.</code>. Let’s now install the modules we will be using.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install django tzdata openai</pre>
<h2>Creating Django Project</h2>
<p>Once the installation is complete, run the following command in your Ubuntu terminal to create a Django project.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">django-admin startproject webassistant .</pre>
<p>This creates a folder with the name <code>webassistant</code>. </p>
<ul>
<li>The <code>.</code> tells Django to create the project in the current directory. </li>
<li>The <code>manage.py</code> file is used to execute several Django commands. </li>
<li>The <code>settings.py</code> in the webassistant folder is the project’s settings. In it, we will register the Django apps we are about to create. </li>
<li>The <code>urls.py</code> is where we will let Django know what it should display to the user. </li>
</ul>
<p>We now check to ensure that the installation went successfully. In your terminal run the following command:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">python3 manage.py runserver</pre>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-141.png" alt="" class="wp-image-1205546" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-141.png 720w, https://blog.finxter.com/wp-content/uploads/2023/03/image-141-300x169.png 300w" sizes="(max-width: 720px) 100vw, 720px" /></figure>
</div>
<p>Once you have seen the above image, congrats! You have successfully installed Django. You can use <code>control C</code> to close the server.</p>
<h2>Creating Django Apps</h2>
<p>Back to your terminal, run the following command to create a Django app.</p>
<p><code>python3 manage.py startapp assistant</code></p>
<p>Use the <code>ls</code> command to see what’s inside the assistant folder.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ls assistant
__init__.py admin.py apps.py migrations models.py tests.py views.py</pre>
<p>The <code>__init__.py</code> file found in both the webassistant and assistant folders enables the folders to be imported as a Python package. The <code>views.py</code> is where we code what we want the browser to be displayed to the user. These files are what concern our project. To know more about other files, check the documentation.</p>
<p>Next, we go to the <code>settings.py</code> file, in <code>INSTALLED_APP</code>S section to register the name of the app we just created. Use the <code>nano</code> command.</p>
<p><code>nano webassistant/settings.py</code></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">...
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # custom app 'assistant',
]</pre>
<p>We also open the project’s <code>urls.py</code> file to register the app-level URLs.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from django.contrib import admin
from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('assistant.urls')),
]</pre>
<p>The <code>path()</code> function is used to map the URL to the appropriate view. The <code>include()</code> function adds the URL of the app to the project-level <code>urls.py</code>. The empty quote means the home URL, that is, what we see when we run the local server.</p>
<p>If you have read Django tutorials including <a href="https://blog.finxter.com/how-i-created-an-url-shortener-app-using-django/" data-type="post" data-id="1196939" target="_blank" rel="noreferrer noopener">this one</a>, you are gradually becoming familiar with the process. That’s how it is done in every Django application.</p>
<h2>Getting the API Key</h2>
<p>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 <a href="https://platform.openai.com/docs/api-reference/introduction" data-type="URL" data-id="https://platform.openai.com/docs/api-reference/introduction" target="_blank" rel="noreferrer noopener">API reference</a> where you will be directed to a page to generate your API key.</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2b50.png" alt="⭐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent/" data-type="post" data-id="1081478" target="_blank" rel="noreferrer noopener">OpenAI API – or How I Made My Python Code Intelligent</a></p>
<p>Make sure you keep the API key safe. Create a file in your app-level folder and call it <code>key.py</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">API_KEY = 'YOUR SECRET API KEY'</pre>
<p>Just replace the text in quotes with your own generated API key.</p>
<h2>Integrating the OpenAI Model</h2>
<p>To integrate the API with our Django application, create a file called <code>engine.py</code> in the app’s folder and input the following python script.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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 chats</pre>
<p>We import the API key and the <code>openai</code> module. We use the <code>openai.api_key</code> to load the API key. Then, in the function, we requested to get the prompt, which is the question asked by the user. We then return the response generated by the model in form of a <a href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank" rel="noreferrer noopener">dictionary</a>.</p>
<p>The 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> The <code>max_tokens</code> specifies the maximum number of tokens or pieces of words that can be generated by the model.</p>
<p>To learn more about the parameters, perhaps <a href="https://www.thetechjournal.com/information-technology/what-is-openai.xhtml" target="_blank" rel="noreferrer noopener">this article</a> can be of help. We will now import the function in our <code>views.py</code> file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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')</pre>
<p>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>try</code> statement will execute. But if there were errors, the code under the <code>except</code> statement will be executed.</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-try-except-an-illustrated-guide/" data-type="post" data-id="367118" target="_blank" rel="noreferrer noopener">Python Try/Except Error Handling</a></p>
<p>The <code>if</code> statement checks if the request method is <code>POST</code>, if so, it will generate a response from the OpenAI model. But if otherwise, the <code>else</code> statement will be run in which no response will be generated.</p>
<p>The <code>render()</code> function renders or displays a response in the HTML files which we are yet to create. Notice that in the <code>else</code> statement, the <code>render()</code> function just renders the same homepage without the context because the request method was not POST. The <code>redirect()</code> function is used to redirect a user to another webpage.</p>
<p>Let’s now write a URL in the <code>urls.py</code> file to display our contents.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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'),
]</pre>
<p>The <code>name</code> argument is kind of an alias for the URL. So instead of writing long URLs, we can just reference them with the name given. Mostly used in HTML files.</p>
<h2>Templates</h2>
<p>We now want to render our templates. Create a folder named <code>templates</code> in the current directory. This is where we will keep our HTML files. Having created the folder, go to <code>settings.py</code> and let Django know that a templates folder is created.</p>
<p>In the <code>settings.py</code> file, scroll down to the ‘<code>TEMPLATES</code>’ section and add the following to <code>DIRS</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">…
TEMPLATES = [ { … 'DIRS': [os.path.join(BASE_DIR, 'templates')], … }
]</pre>
<p>Be sure to import the <a href="https://blog.finxter.com/exploring-pythons-os-module/" data-type="post" data-id="19050" target="_blank" rel="noreferrer noopener"><code>os</code> module</a>. Then, create a file in the templates folder with the name <code>base.html</code></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;html lang="en">
&lt;head> &lt;meta charset="UTF-8"> &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"> &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"> &lt;title>Web Assistant | {% block title %} {% endblock %}&lt;/title> &lt;link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
&lt;/head>
&lt;body> {% block content %} {% endblock %}
&lt;/body>
&lt;/html>
</pre>
<p>That’s our HTML boilerplate with bootstrap added to it for styling our web pages. Next is the <code>home.html</code>, the homepage that will inherit everything in the <code>base.html</code> template.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{% extends 'base.html' %}
{% block title %} Home {% endblock %}
{% block content %}
&lt;div class="row justify-content-center my-4"> &lt;div class="col-md-7 mt-4"> &lt;div class="card"> &lt;h1 class="card-header text-center">A.I WEB ASSISTANT&lt;/h1> &lt;div class="card-body"> &lt;pre>Hello, how can I help you?&lt;/pre> &lt;form action="." method="POST"> &lt;!-- this secures the form from malicious attacks during submission --> {% csrf_token %} &lt;input class="form-control mb-2" required type="text" autofocus="autofocus" name="prompt" value="{{ prompt }}" id=""> &lt;button class="btn btn-success fw-bold" type="submit"> GENERATE &lt;/button> &lt;/form> &lt;hr> &lt;pre> {{ response }} &lt;/pre> &lt;/div> &lt;/div> &lt;/div> &lt;/div>
&lt;/div>
{% endblock %}
</pre>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-142.png" alt="" class="wp-image-1205585" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-142.png 720w, https://blog.finxter.com/wp-content/uploads/2023/03/image-142-300x169.png 300w" sizes="(max-width: 720px) 100vw, 720px" /></figure>
</div>
<p>Finally, the <code>error.html</code> will be displayed when an error occurs. It also inherits everything in the <code>base.html</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{% extends 'base.html' %}
{% block title %} 404 {% endblock %}
{% block content %}
&lt;div class="row justify-content-center my-4"> &lt;div class="col-md-7 mt-4"> &lt;h1>Page Not Found&lt;/h1> &lt;p>Make sure you are connected to the internet or your query is correct&lt;/p> &lt;a href="{% url 'home' %}" class="btn btn-secondary">Home&lt;/a> &lt;/div>
&lt;/div>
{% endblock %}
</pre>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-143.png" alt="" class="wp-image-1205590" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-143.png 720w, https://blog.finxter.com/wp-content/uploads/2023/03/image-143-300x169.png 300w" sizes="(max-width: 720px) 100vw, 720px" /></figure>
</div>
<p>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>block</code> statement, it must end with an <code>endblock</code> statement. In <code>base.html</code>, we inserted the empty block statement in the title tag.</p>
<p>This 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.html</code>.</p>
<p>The <code>csrf_token</code> is for security reasons. It’s compulsory. If you don’t add it, Django will throw an error. The prompt variable comes from the <code>view.py</code> file which in turn is imported from the <code>engine.py</code> file. The same applies to the response. Remember, we sent them here using the <code>render()</code> function.</p>
<p>The <code>{% url 'home' %}</code> syntax is Django’s way of displaying internal URLs. Go back to the app-level <code>urls.py</code>, you will see where we defined the name and this makes it possible to use it in HTML files.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-144.png" alt="" class="wp-image-1205591" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-144.png 720w, https://blog.finxter.com/wp-content/uploads/2023/03/image-144-300x169.png 300w" sizes="(max-width: 720px) 100vw, 720px" /></figure>
</div>
<h2>Conclusion</h2>
<p>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.</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2b50.png" alt="⭐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-i-created-an-url-shortener-app-using-django/" data-type="post" data-id="1196939" target="_blank" rel="noreferrer noopener">How I Created an URL Shortener App Using Django</a></p>
</div>


https://www.sickgaming.net/blog/2023/03/13/how-i-built-an-openai-powered-web-assistant-with-django/