Ai chatbot

Building a Multifunctional AI Chatbot Using Django and OpenRouter AI API

Introduction

AI chatbots are transforming the way we interact with applications, making communication seamless and efficient. In this guide, we will build a multifunctional AI chatbot in Django using the OpenRouter AI API. Our chatbot will:

โœ… Real-time AI Conversations
๐ŸŽ™๏ธ Voice Recognition
๐Ÿ”Š Text-to-Speech Responses
๐Ÿ’พ Chat History & Export
๐ŸŒ Multilanguage Support
โšก Fast & Secure API


Step 1: Set Up Django Project

1๏ธโƒฃ Install Django and Dependencies

Run the following command in your terminal:

pip install django djangorestframework openai pdfplumber python-docx Pillow SpeechRecognition gtts

2๏ธโƒฃ Create Django Project and App

django-admin startproject ai_agent
cd ai_agent
django-admin startapp agent_app

3๏ธโƒฃ Configure settings.py

Inside ai_agent/settings.py, add:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'agent_app',
]

Step 2: Build the AI Chatbot with OpenRouter AI API

We will use the OpenRouter AI API to process text prompts.

1๏ธโƒฃ Update views.py

Inside agent_app/views.py:

import requests
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
import speech_recognition as sr
from gtts import gTTS
import os

OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions"
OPENROUTER_API_KEY = "your_api_key_here"

@csrf_exempt
def chatbot(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        user_input = data.get("message", "")

        response = requests.post(
            OPENROUTER_API_URL,
            headers={"Authorization": f"Bearer {OPENROUTER_API_KEY}"},
            json={"messages": [{"role": "user", "content": user_input}]}
        )
        return JsonResponse(response.json())
    return JsonResponse({"error": "Invalid request"}, status=400)

@csrf_exempt
def voice_to_text(request):
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = recognizer.listen(source)
    try:
        text = recognizer.recognize_google(audio)
        return JsonResponse({"message": text})
    except sr.UnknownValueError:
        return JsonResponse({"error": "Could not understand audio"})

@csrf_exempt
def text_to_speech(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        text = data.get("message", "")
        tts = gTTS(text=text, lang='en')
        tts.save("response.mp3")
        return JsonResponse({"audio": "response.mp3"})
    return JsonResponse({"error": "Invalid request"}, status=400)

Step 3: Handle File Uploads and Text Extraction

1๏ธโƒฃ Update views.py to Extract Text from Files

from django.core.files.storage import default_storage
from pdfplumber import open as pdf_open
from docx import Document

def extract_text_from_file(file_path):
    ext = file_path.split('.')[-1]
    if ext == "pdf":
        with pdf_open(file_path) as pdf:
            return "\n".join([page.extract_text() for page in pdf.pages])
    elif ext == "docx":
        doc = Document(file_path)
        return "\n".join([para.text for para in doc.paragraphs])
    return "Unsupported file format."

Step 4: Create URL Routes

Inside agent_app/urls.py:

from django.urls import path
from .views import chatbot, voice_to_text, text_to_speech

urlpatterns = [
    path('chatbot/', chatbot, name='chatbot'),
    path('voice-to-text/', voice_to_text, name='voice_to_text'),
    path('text-to-speech/', text_to_speech, name='text_to_speech'),
]

Now, add this to ai_agent/urls.py:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('agent_app.urls')),
]

Step 5: Build the Frontend UI

Inside agent_app/templates/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chatbot</title>
    <script>
        async function sendMessage() {
            let userInput = document.getElementById("message").value;
            let response = await fetch("/api/chatbot/", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ message: userInput })
            });
            let data = await response.json();
            document.getElementById("response").innerText = data.choices[0].message.content || "Error";
        }
    </script>
</head>
<body>
    <h2>AI Chatbot</h2>
    <input type="text" id="message" placeholder="Type your message...">
    <button onclick="sendMessage()">Send</button>
    <p id="response"></p>
</body>
</html>

images:

GitHub Repository: AI Chatbot
Live Demo: AI Chatbot - Hosted Link


Conclusion

๐ŸŽฏ Now, your AI chatbot supports:
โœ… Real-time AI Conversations
๐ŸŽ™๏ธ Voice Recognition
๐Ÿ”Š Text-to-Speech Responses
๐Ÿ’พ Chat History & Export
๐ŸŒ Multilanguage Support
โšก Fast & Secure API

๐Ÿš€ Let me know if you need further improvements! ๐Ÿ”ฅ

0
Subscribe to my newsletter

Read articles from YANAMADALA RAJESH directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

YANAMADALA RAJESH
YANAMADALA RAJESH