How to integrate rasa open source to the Django running website

Published July 28, 2024, 10:15 a.m. by cloudblog

Integrating Rasa Open Source with a Django website involves several steps to ensure that your chatbot can interact seamlessly with your existing Django application. Here’s a step-by-step guide to help you through the integration process:

Integrating Rasa Open Source with a Django website involves several steps to ensure that your chatbot can interact seamlessly with your existing Django application. Here’s a step-by-step guide to help you through the integration process:

### 1. Set Up Rasa Open Source

1. **Install Rasa Open Source**:
   Ensure that you have Rasa installed. You can install it using pip:
   ```bash
   pip install rasa
   ```

2. **Create a New Rasa Project**:
   If you don’t already have a Rasa project, create one:
   ```bash
   rasa init
   ```
   This will generate a basic project structure for you.

3. **Train Your Model**:
   Train your Rasa model using the training data provided in the `data` folder:
   ```bash
   rasa train
   ```

4. **Run the Rasa Server**:
   Start the Rasa server, which will be responsible for handling requests to your chatbot:
   ```bash
   rasa run
   ```

### 2. Set Up Your Django Project

1. **Install Required Packages**:
   Ensure you have Django installed. If not, install it using pip:
   ```bash
   pip install django
   ```

2. **Create a Django Project**:
   If you don’t have a Django project set up, create one:
   ```bash
   django-admin startproject myproject
   ```

3. **Create a Django App**:
   Inside your Django project, create a new app where you will add the integration logic:
   ```bash
   python manage.py startapp chatbot
   ```

### 3. Integrate Rasa with Django

1. **Create a View for Chatbot Interaction**:
   In your Django app, create a view that will handle interactions between the Django frontend and the Rasa server.

   ```python
   # chatbot/views.py

   import requests
   from django.http import JsonResponse
   from django.views.decorators.csrf import csrf_exempt
   import json

   @csrf_exempt
   def chat(request):
       if request.method == 'POST':
           user_message = json.loads(request.body.decode('utf-8')).get('message')
           response = requests.post('http://localhost:5005/webhooks/rest/webhook', json={'message': user_message})
           rasa_response = response.json()
           return JsonResponse({'responses': rasa_response})
       return JsonResponse({'error': 'Invalid request'}, status=400)
   ```

2. **Add URL Routing**:
   Add a URL route for the chat view in your Django app’s `urls.py`.

   ```python
   # chatbot/urls.py

   from django.urls import path
   from .views import chat

   urlpatterns = [
       path('chat/', chat, name='chat'),
   ]
   ```

   Then, include this URL configuration in your project's `urls.py`.

   ```python
   # myproject/urls.py

   from django.contrib import admin
   from django.urls import path, include

   urlpatterns = [
       path('admin/', admin.site.urls),
       path('chatbot/', include('chatbot.urls')),
   ]
   ```

3. **Set Up Frontend Interaction**:
   On the frontend, you’ll need to set up a form or WebSocket connection to send messages to your Django view and display the responses.

   Here’s a basic example using JavaScript with fetch API:

   ```html
   <!-- template.html -->
   <html>
   <body>
       <input type="text" id="messageInput" placeholder="Type a message..."/>
       <button onclick="sendMessage()">Send</button>
       <div id="chatBox"></div>

       <script>
           function sendMessage() {
               const message = document.getElementById('messageInput').value;
               fetch('/chatbot/chat/', {
                   method: 'POST',
                   headers: {
                       'Content-Type': 'application/json',
                   },
                   body: JSON.stringify({ 'message': message }),
               })
               .then(response => response.json())
               .then(data => {
                   const chatBox = document.getElementById('chatBox');
                   data.responses.forEach(response => {
                       chatBox.innerHTML += `<p>${response.text}</p>`;
                   });
               });
           }
       </script>
   </body>
   </html>

Share this post

Similar posts

There are no similar posts yet.

0 comments

There are no comments.

Add a new comment