Debug School

rakesh kumar
rakesh kumar

Posted on

How to integrate chat gpt Api Using the Official openai Library in Django

Install the OpenAI library:

$ pip install openai
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:

OPENAI_API_KEY = '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'
Enter fullscreen mode Exit fullscreen mode

Create forms

from django import forms
from .models import Employee


class EmployeeForm(forms.ModelForm):

    class Meta:
        model = Employee
        fields = ('fullname','mobile','emp_code','position')
        labels = {
            'fullname':'Full Name',
            'emp_code':'EMP. Code'
        }

    def __init__(self, *args, **kwargs):
        super(EmployeeForm,self).__init__(*args, **kwargs)
        self.fields['position'].empty_label = "Select"
        self.fields['emp_code'].required = False


class ChatForm(forms.Form):
    message = forms.CharField(label='Message', max_length=100) 
Enter fullscreen mode Exit fullscreen mode

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

Create your models here.

class Position(models.Model):
    title = models.CharField(max_length=50)

    def __str__(self):
        return self.title

class Employee(models.Model):
    fullname = models.CharField(max_length=100)
    emp_code = models.CharField(max_length=3)
    mobile= models.CharField(max_length=15)
    position= models.ForeignKey(Position,on_delete=models.CASCADE)
    image = ImageField()

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

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

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

            # Make a request to ChatGPT using the OpenAI library
            openai.api_key = settings.OPENAI_API_KEY
            response = openai.Completion.create(
                engine='gpt-3.5-turbo',
                prompt=user_input,
                max_tokens=50
            )

            if response.choices:
                generated_message = response.choices[0].text.strip()
                print(generated_message)
            else:
                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, 'chat.html', {'form': form, 'generated_message': generated_message})
    else:
        form = ChatForm()

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

Create a template file named chat.html to display the generated message. In your chat.html file, you can add the following code:

<html>
<head>
    <title>ChatGPT</title>
</head>
<body>
    <h1>ChatGPT</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Send">
    </form>
    {% if generated_message %}
    <h2>Generated Message:</h2>
    <p>{{ generated_message }}</p>

    {% else %}
    <h1>Generated Message will display after data is saved into database:</h1>
    {% endif %}
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Run your Django server:

$ python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Access the chat page in your browser at**

http://localhost:8000/chatgpt/.

Enter a message in the input field and click "Send". The generated response from ChatGPT will be displayed on the page.

This example demonstrates how to integrate ChatGPT into your Django project, send user input to ChatGPT using the OpenAI library, and display the generated response in a template file.

output

Image description

Top comments (0)