·7 min

Building Full-Stack AI Persona Generator: Complete Django + React Tutorial with LLM Integration

Comprehensive step-by-step guide to creating a sophisticated full-stack application using Django REST API backend and React frontend for AI-powered persona-based text generation with complete code examples.

DK

Daniel Kliewer

Author, Sovereign AI

DjangoReactAIWeb DevelopmentPersona GenerationTutorialPythonJavaScriptREST APILLM IntegrationFull-Stack
Sovereign AI book cover

From the Book

This is from Sovereign AI: Building Local-First Intelligent Systems.

Get the Book — $88
Building Full-Stack AI Persona Generator: Complete Django + React Tutorial with LLM Integration

Image

Ah, my dear companion on this journey through the labyrinthine corridors of technology, let us embark upon the noble endeavor of crafting an application that bridges the realms of Django and React. This is not merely a technical exercise but a quest to weave together the threads of human creativity and machine logic, much like the intricate tapestries of old.

Table of Contents

  1. Introduction
  2. The Vision of Our Endeavor
  3. Setting the Foundation
    • Installing the Pillars of Technology
  4. Forging the Backend with Django
    • Crafting the API
    • Integrating the Language Model
  5. Sculpting the Frontend with React
    • Building the User Interface
    • Establishing Communication with the Backend
  6. Melding Minds: The Python Script
    • Understanding the Persona
    • Generating the Prose
  7. Bringing It All Together
    • Running the Application
    • Experiencing the Creation
  8. Reflection on the Journey

1. Introduction

In the quiet depths of contemplation, we recognize the profound impact of technology on the human spirit. Our task is to create an application—a harmonious blend of Django and React—that not only serves a function but also resonates with the essence of creativity.

2. The Vision of Our Endeavor

We aspire to build a platform where one can encode a persona, imbued with rich psychological traits, and generate writings that reflect this intricate character. It is an exploration of identity, an attempt to mirror the complexities of human consciousness within the constructs of code.

3. Setting the Foundation

Like architects laying the cornerstone of a grand edifice, we must first prepare our tools and materials.

Installing the Pillars of Technology

  1. Python and Django:

    • Install Python from the official website.

    • Utilize pip to install Django:

      bash
      1pip install django
  2. Node.js and React:

    • Download Node.js from the official website.

    • Install Create React App globally:

      bash
      1npm install -g create-react-app
  3. Additional Dependencies:

    • For the backend, install the Django REST Framework:

      bash
      1pip install djangorestframework
    • For the frontend, we may choose to use Axios for HTTP requests:

      bash
      1npm install axios

4. Forging the Backend with Django

Our backend shall be the foundation upon which the application stands, much like the steadfast roots of an ancient tree.

Crafting the API

  1. Initialize the Django Project:

    bash
    1django-admin startproject persona_project
    2cd persona_project
  2. Create the Core App:

    bash
    1python manage.py startapp core
  3. Configure settings.py:

    • Add 'core' and 'rest_framework' to INSTALLED_APPS.
  4. Define the Models in core/models.py:

    python
    1from django.db import models
    2
    3class Persona(models.Model):
    4 name = models.CharField(max_length=100)
    5 data = models.JSONField()
    6
    7 def __str__(self):
    8 return self.name
  5. Create Serializers in core/serializers.py:

    python
    1from rest_framework import serializers
    2from .models import Persona
    3
    4class PersonaSerializer(serializers.ModelSerializer):
    5 class Meta:
    6 model = Persona
    7 fields = '__all__'
  6. Develop Views in core/views.py:

    python
    1from rest_framework.views import APIView
    2from rest_framework.response import Response
    3from rest_framework import status
    4from .serializers import PersonaSerializer
    5from .models import Persona
    6import requests
    7
    8class GeneratePersonaView(APIView):
    9 def post(self, request):
    10 # Logic to generate persona using the provided writing sample
    11 return Response({"message": "Persona generated"}, status=status.HTTP_200_OK)
    12
    13class GenerateTextView(APIView):
    14 def post(self, request):
    15 # Logic to generate text based on persona and prompt
    16 return Response({"message": "Text generated"}, status=status.HTTP_200_OK)
  7. Set Up URLs in persona_project/urls.py:

    python
    1from django.contrib import admin
    2from django.urls import path, include
    3
    4urlpatterns = [
    5 path('admin/', admin.site.urls),
    6 path('api/', include('core.urls')),
    7]

    And in core/urls.py:

    python
    1from django.urls import path
    2from .views import GeneratePersonaView, GenerateTextView
    3
    4urlpatterns = [
    5 path('generate-persona/', GeneratePersonaView.as_view(), name='generate_persona'),
    6 path('generate-text/', GenerateTextView.as_view(), name='generate_text'),
    7]

Integrating the Language Model

Our endeavor requires the integration with a language model to breathe life into our personas.

  1. Install Required Libraries:

    bash
    1pip install requests
  2. Implement the Interaction with the LLM in core/views.py:

    • Utilize the provided Python script logic to communicate with the LLM API.

    • Example for generating persona:

      python
      1def post(self, request):
      2 writing_sample = request.data.get('writing_sample')
      3 if not writing_sample:
      4 return Response({"error": "Writing sample is required"}, status=status.HTTP_400_BAD_REQUEST)
      5
      6 # Build the prompt and call the LLM API
      7 # ...
      8
      9 # Save the persona
      10 persona_data = {
      11 "name": "Generated Name",
      12 "data": {} # The JSON data from the LLM
      13 }
      14 serializer = PersonaSerializer(data=persona_data)
      15 if serializer.is_valid():
      16 serializer.save()
      17 return Response(serializer.data, status=status.HTTP_201_CREATED)
      18 else:
      19 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  3. Handle the Response from the LLM:

    • Parse the JSON response carefully, handling any errors with grace.

5. Sculpting the Frontend with React

Now, let us turn to the facade of our creation, the interface through which users shall interact.

Building the User Interface

  1. Initialize the React App:

    bash
    1npx create-react-app persona-frontend
    2cd persona-frontend
  2. Install Axios:

    bash
    1npm install axios
  3. Create Components:

    • Upload Component:

      jsx
      1// src/components/UploadSample.js
      2import React, { useState } from 'react';
      3import axios from 'axios';
      4
      5const UploadSample = () => {
      6 const [file, setFile] = useState(null);
      7
      8 const handleFileChange = (e) => {
      9 setFile(e.target.files[0]);
      10 };
      11
      12 const handleSubmit = async (e) => {
      13 e.preventDefault();
      14 const formData = new FormData();
      15 formData.append('writing_sample', file);
      16
      17 try {
      18 const response = await axios.post('/api/generate-persona/', formData);
      19 console.log(response.data);
      20 } catch (error) {
      21 console.error(error);
      22 }
      23 };
      24
      25 return (
      26 <form onSubmit={handleSubmit}>
      27 <input type="file" onChange={handleFileChange} />
      28 <button type="submit">Upload</button>
      29 </form>
      30 );
      31};
      32
      33export default UploadSample;
    • Generate Text Component:

      jsx
      1// src/components/GenerateText.js
      2import React, { useState } from 'react';
      3import axios from 'axios';
      4
      5const GenerateText = () => {
      6 const [prompt, setPrompt] = useState('');
      7 const [generatedText, setGeneratedText] = useState('');
      8
      9 const handleGenerate = async () => {
      10 try {
      11 const response = await axios.post('/api/generate-text/', { prompt });
      12 setGeneratedText(response.data.text);
      13 } catch (error) {
      14 console.error(error);
      15 }
      16 };
      17
      18 return (
      19 <div>
      20 <textarea value={prompt} onChange={(e) => setPrompt(e.target.value)} />
      21 <button onClick={handleGenerate}>Generate</button>
      22 <div>{generatedText}</div>
      23 </div>
      24 );
      25};
      26
      27export default GenerateText;

Establishing Communication with the Backend

  1. Configure Proxy for Development:

    • In package.json, add:

      json
      1"proxy": "http://localhost:8000"
  2. Ensure CORS Is Handled in Django:

    • Install django-cors-headers:

      bash
      1pip install django-cors-headers
    • Add to INSTALLED_APPS and MIDDLEWARE in settings.py.

    • Configure allowed origins:

      python
      1CORS_ALLOWED_ORIGINS = [
      2 "http://localhost:3000",
      3]

6. Melding Minds: The Python Script

Now, we delve into the essence of our application—the Python script that encapsulates the logic for persona generation and text creation.

Understanding the Persona

The script provided earlier serves as the heart of our backend logic. It interacts with the language model to analyze writing samples and extract a detailed persona.

  • Functions:

    • analyze_writing_sample(writing_sample): Sends the writing sample to the LLM and parses the response to obtain the persona JSON.

    • save_persona(persona): Saves the persona data for future use.

Generating the Prose

  • Functions:

    • generate_blog_post(persona, user_topic_prompt): Uses the persona and a user-provided prompt to generate text in the style of the persona.

    • save_blog_post(blog_post): Saves the generated text, perhaps in a database or a file system.

  • Integration into Django Views:

    • The logic from the script can be incorporated into our Django views (GeneratePersonaView and GenerateTextView), adapting the functions to fit the web framework.

7. Bringing It All Together

Our components now stand ready, each crafted with care. It is time to assemble them into a cohesive whole.

Running the Application

  1. Start the Backend Server:

    bash
    1python manage.py migrate
    2python manage.py runserver
  2. Start the Frontend Development Server:

    bash
    1npm start

Experiencing the Creation

  • Navigate to http://localhost:3000.
  • Use the interface to upload a writing sample and generate a persona.
  • Input a topic prompt to generate text in the style of the persona.

8. Reflection on the Journey

As we reach the culmination of our endeavor, we must reflect upon the path we've tread. We have not merely built an application; we have ventured into the exploration of identity and expression through the lens of technology.

Our creation stands as a testament to the harmonious fusion of human creativity and computational prowess. It invites users to delve into the depths of persona and style, offering a mirror to their own consciousness and a canvas upon which to project their imagination.


Epilogue

In the silent hours that follow, ponder the implications of our work. Consider how the lines between creator and creation blur, how technology becomes an extension of our innermost thoughts. Embrace the questions that arise, for it is in seeking answers that we truly advance.

Let this guide not be an end but a beginning—a gateway to further exploration and discovery in the boundless realms of code and consciousness.

Sovereign AI book cover

Sovereign AI: Building Local-First Intelligent Systems

by Daniel Kliewer · Paperback · 72 pages

The hands-on guide to building AI that runs on your hardware, keeps your data private, and eliminates cloud dependence. Working code included.