Debug School

rakesh kumar
rakesh kumar

Posted on

How to integrate chatbot application with request body parameter using open ai api using django

Install the OpenAI library:

$ pip install openai
Enter fullscreen mode Exit fullscreen mode
import openai im models,view file
Enter fullscreen mode Exit fullscreen mode

Obtain your OpenAI API key and store it in your Django project's settings. Open your **project's settings.py file and add the following line*:
**go to site
*

https://platform.openai.com/account/api-keys
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

OPENAI_API_KEY = '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

Create forms

from django import forms
from .models import Employee
from .models import Category
from .models import Chatcategory

class ChatForm(forms.Form):
    message = forms.CharField(label='Message',widget=forms.Textarea(attrs={'id': 'my-textarea','maxlength': '1000','class': 'centered-textarea',
            'style': 'height: 300px; width: 500px; margin-left: 2%;'}))
Enter fullscreen mode Exit fullscreen mode

Create your models here.

from django.db import models
from sorl.thumbnail import ImageField
from django.conf import settings
import openai


class ChatMessage(models.Model):
    message = models.CharField(max_length=100)
    generated_message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.message
Enter fullscreen mode Exit fullscreen mode

Run migrate commands after adding function in modal and forms

python manage.py makemigrations loginsignup
python manage.py sqlmigrate loginsignup 0001
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Create a new Django view in your views.py file:

import openai
from django.shortcuts import render

openai.api_key = settings.OPENAI_API_KEY # Replace with your OpenAI API key

def chat_with_gpt(request):
    if request.method == 'POST':
        form = ChatForm(request.POST)
        if form.is_valid():
            user_input = form.cleaned_data['message'] 

            dynamic_max_tokens =  request.POST.get('max_tokens')  
            dynamic_top_p = request.POST.get('top_p') 
            dynamic_temperature = request.POST.get('temperature') 
            dynamic_modal = request.POST.get('modal')
            dynamic_frequency_penalty = request.POST.get('frequency_penalty') 
            dynamic_presence_penalty = request.POST.get('presence_penalty') 

            max_tokens = int(dynamic_max_tokens) if dynamic_max_tokens and dynamic_max_tokens != '0' else 100          
            modal = dynamic_modal if dynamic_modal and dynamic_modal != '0' else "text-davinci-003"
            temperature = float(dynamic_temperature) if dynamic_temperature and dynamic_temperature != '0' else 0.5
            top_p = float(dynamic_top_p) if dynamic_top_p and dynamic_top_p != '0' else 0.5
            frequency_penalty = float(dynamic_frequency_penalty) if dynamic_frequency_penalty and dynamic_frequency_penalty != '0' else 0.5
            presence_penalty = float(dynamic_presence_penalty) if dynamic_presence_penalty and dynamic_presence_penalty != '0' else 0
            data = {
                'user_input':form.cleaned_data['message'],
                'temperature':temperature,
                'max_tokens':request.POST.get('max_tokens'),
                'top_p':top_p,
            }
            # Print all the request data
            print('Request Data:', data)
            # Make a request to ChatGPT using the OpenAI library

            openai.api_key = settings.OPENAI_API_KEY
            response = openai.Completion.create(
                model=modal,
                prompt=user_input,
                temperature=temperature,
                max_tokens=max_tokens,
                top_p=top_p,
                frequency_penalty=frequency_penalty,
                presence_penalty=presence_penalty,
                logprobs=0,
                echo=True
            )

            if response.choices:
                print('data 200 choices')
                generated_message = response.choices[0].text.strip()
                print(generated_message)
            else:
                print('data else choices')
                generated_message = 'Failed to generate response'
            # Save the user input and generated response to the database
            chat_message = ChatMessage(message=user_input, generated_message=generated_message)
            chat_message.save()

            return render(request, 'chatgpt.html', {'form': form, 'generated_message': generated_message})
    else:
        form = ChatForm()

    return render(request, 'chatgpt.html', {'form': form})
Enter fullscreen mode Exit fullscreen mode

in chatgpt.html inside template

<html>
<head>
    <title>ChatGPT</title>
</head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<style>
     .content {
      text-align: center;
    }
    .headcontent {
      text-align: center;
    }
    .rightcontent {
      text-align: right;
    }
  </style>
<body >
  <h1 class="headcontent">ChatGPT using model</h1>
  <div class="container-fluid mt-3">

    <form  method="post">
      {% csrf_token %}
    <div class="row">

      <div class="col p-3"></div>
      <div class="col p-3">  {{ form.as_p }}
        <input type="submit" value="Send"></div>

      <div class="col p-3">
        <div class="form-group mt-4"> 
          <label for="model">Model:</label>
          <select id="model" name="model">    

            <option value="text-davinci-003">text-davinci-003</option>
              <option value="text-ada-001">text-ada-001</option>
              <option value="text-curie-001">text-curie-001</option>
              <option value="text-babbage-001">text-babbage-001</option>
          </select>
         </div>
        <div class="form-group mt-4"> 
        <label for="temperature">Temperature:</label>     

        <input type="range" min="0" max="1" step="0.1" value="0.0" name="temperature" id="temperature" class="temperature-slider">
    <span id="temperature_value">0.0</span>  
       </div>
        <div class="form-group mt-4">   
        <label for="max_tokens">Max Tokens:</label>  
        <input type="range" min="0" max="4000" step="1.0" value="0.0" name="max_tokens" id="max_tokens" class="max_tokens-slider">
    <span id="max_tokens_value">0.0</span>                 

    </div>

      <div class="form-group mt-4"> 
        <label for="top_p">Top P:</label> 
        <input type="range" min="0" max="1" step="0.1" value="0.0" name="top_p" id="top_p" class="top_p_slider">
    <span id="top_p_value">0.0</span>  

    </div>
    <div class="form-group mt-4"> 
      <label for="fre_p">Frequency penalty</label>                 
      <input type="range" min="0" max="1" step="0.1" value="0.0" name="frequency_penalty" id="frequency_penalty" class="frequency-penalty-slider">
      <span id="frequency_penalty_value">0.0</span>      
  </div>
  <div class="form-group mt-4"> 
    <label for="pre_p">Presence penalty</label>                 
    <input type="range" min="0" max="1" step="0.1" value="0.0" name="presence_penalty" id="presence_penalty" class="presence-penalty-slider">
    <span id="presence_penalty_value">0.0</span>    
</div>

</div>



   </div>

  </form>
  {% if generated_message %}
  <h2 class="headcontent">Generated Message:</h2>
  <p  class="headcontent">{{ generated_message }}</p>

  {% else %}
  <h1  class="headcontent">Generated Message will display after data is saved into database:</h1>
  {% endif %}
  </div>

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> 

  <script>
    // Update the displayed frequency penalty value based on the slider input


    const frequencyPenaltySlider = document.getElementById('frequency_penalty');
    const frequencyPenaltyValue = document.getElementById('frequency_penalty_value');

    frequencyPenaltySlider.addEventListener('input', () => {
      frequencyPenaltyValue.textContent = frequencyPenaltySlider.value;
    });
    const tempratureSlider = document.getElementById('temperature');
    const tempratureValue = document.getElementById('temperature_value');

    tempratureSlider.addEventListener('input', () => {
      tempratureValue.textContent = tempratureSlider.value;
    });

    const maxtokensSlider = document.getElementById('max_tokens');
    const maxtokensValue = document.getElementById('max_tokens_value');

    maxtokensSlider.addEventListener('input', () => {
      maxtokensValue.textContent = maxtokensSlider.value;
    });

    const toppslider = document.getElementById('top_p');
    const toppvalue = document.getElementById('top_p_value');

    toppslider.addEventListener('input', () => {
      toppvalue.textContent = toppslider.value;
    });

    const presencePenaltySlider = document.getElementById('presence_penalty');
    const presencePenaltyValue = document.getElementById('presence_penalty_value');

    presencePenaltySlider.addEventListener('input', () => {
      presencePenaltyValue.textContent = presencePenaltySlider.value;
    });

  </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)