Questions icon indicating copy to clipboard operation
Questions copied to clipboard

blank box Response issue while fetching response

Open My-CMDhub opened this issue 1 year ago • 0 comments

Can someone help me to solve the issue of blank box response of the chatbot. every time I have to reload the page to see the response. You can see the attached picture:

Screenshot 2024-04-26 at 10 34 00 am

I attached my code below:

  1. **HTML & JS: **
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
    <title>Chatbot</title>
    
    
     
</head>
<body>
    
    <div id="chatContainer" class="chathidde">
    
        
        <div class="chat" id="chatMessages">
            <div class="nav_icon">
                <img width="48" height="48" src="https://img.icons8.com/color/48/message-bot.png" alt="message-bot"/>

            <div class="bot_nav">
                ChatBot
                
            </div>
        </div>
            
            <div class="coming_message" id= "comingmessage">
                <pre class="start_message"> Hello👋!! It's Great to see you. 
 Welcome to our bord,
<span><b> Let's blend your cravings with our 
 creamy creations!</b> </span> </pre>
          
                <div class="icon"> <img width="40" height="40" src="https://img.icons8.com/color/48/message-bot.png" alt="message-bot"/>
                    
               </div>
            </div>
            <div class="options">
                <a href="https://www.aghajuicetruganina.com.au" class="online_order">Online Order</a>
                
    </div>
             <br><br><br><br><br><br><br><br><br><br>
             
             
        {% for message in chat_history %}
                {% if message.user %}
                <span class="emoji1"><img width="64" height="64" src="https://img.icons8.com/offices/30/person-male-skin-type-4.png" alt="user-male-circle"/></span>

                <div id="user" class="message user-message">
                     {{ message.user }}
                </div>
                {% endif %}
                
              
                <span class="emoji2"><img  width="40" height="40" src="https://img.icons8.com/color/48/message-bot.png" alt="message-bot"/></span>
                <div class="message bot-message">
                   
                    {{ message.bot | safe }} 
                </div>
                
                <div style="margin-bottom: 10px;"></div> 
                
                
               
            {% endfor %}
        <br><br><br><br>

            
        <div class="chatbot"  >
            <form id="chatForm" method="POST" >
                <div class="textbar">
                    <input type="text" name="user_input" id="user_input" placeholder="Type your message.." required>
                    <button id="send" type="submit" > <img width="23" height="23" src="https://img.icons8.com/ios-glyphs/30/filled-sent.png" alt="filled-sent"/>
                    </button>
                </div>
                <div class="creator">
                    <h4>Custom DevOp Powered with (<a href="https://openai.com"><b>Openai</b></a>)</h4>
                </div>
            </form>
        </div>
        
    </div>
    

</div>
<div class="togal_icon" id="toggleIcon">
    <img width="40" height="43" src="https://img.icons8.com/ios-filled/50/000000/chat-message--v1.png" alt="chat-message--v1"/>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script>
   
   $(function () {
            $('#selectlist').change(function () {
                var sel = $(this).val();
                var input = document.getElementById("input").value;
                $.ajax({
                    url: "/Pikatro/bot",
                    contentType: "application/json; charset=utf-8",
                    type: "post",
                    data: JSON.stringify({
                        sel: sel,
                        input: input
                    }),
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                    }
                });
            });

            // Handle form submission
            $('#chatForm').submit(function (event) {
                event.preventDefault(); // Prevent default form submission

                // Get the user input
                var userInput = $('#user_input').val();
                $('#user_input').val('');

                $('#chatMessages').scrollTop($('#chatMessages')[0].scrollHeight);

                // Append the user's message to the chat interface
                $('#chatMessages').append('<div class="message user-message">' + userInput + '</div>');

                // Send AJAX request to the server
                $.ajax({
                    type: 'POST', // Use POST method
                    url: '/Pikatro/bot', // Specify Flask endpoint
                    data: { 'user_input': userInput }, // Send user input as data
                    success: function (response) {
                        // Clear the input field
                        $('#user_input').val('');

                        // Append the bot's response to the chat interface
                        $('#chatMessages').append('<div class="message bot-message">' + response + '</div>');
                        $('#chatMessages').scrollTop($('#chatMessages')[0].scrollHeight);
                    },
            error: function(xhr, status, error) {
                console.error('Error:', error);
            }
        });
        return false;
    });
});


        function initializeChatToggle() {
            document.addEventListener('DOMContentLoaded', function() {
                var chatContainer = document.getElementById('chatContainer');
                var toggleIcon = document.querySelector('.togal_icon img');
        
                toggleIcon.addEventListener('click', function() {
                    chatContainer.classList.toggle('chathidde'); // Toggle the visibility class
                });
            });
            
        }

        
        // Call the function to initialize the chat toggle behavior
        initializeChatToggle();
 </script>

</body>
</html>

  1. **Flask (app.py): **
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy 
from datetime import datetime
from markupsafe import escape
import os
import re
from llama_index.core import StorageContext, load_index_from_storage


os.environ["OPENAI_API_KEY"] = 'api_key'

app = Flask(__name__)



# Load the index from disk
def load_index_from_disk():
   storage_context = StorageContext.from_defaults(persist_dir="PKL_file")
   new_index = load_index_from_storage(storage_context)
   return new_index

# Initialize loaded_index outside of the Flask app
loaded_index = load_index_from_disk()




# Route to handle bot requests
chat_history = []
@app.route('/Pikatro/bot', methods=['GET','POST'])
def pikatro_bot():

    if request.method == 'POST':
        # Get the user input from the form
        user_input = request.form.get('user_input')
        
        # Process user input with chatbot engine
        response = process_user_input(user_input)
        
        # Append the user input and bot response to chat_history
        chat_history.append({'user': user_input, 'bot': response})
        
        # Redirect to the same route to clear the form and display the updated chat history
        return redirect(url_for('pikatro_bot'))
   
    # Render the template with the chat history
    return render_template('bot_template.html', chat_history=chat_history)




# Custom responses
custom_responses = {
    "greeting": "Hi there! WELCOME TO AGHA JUCIE. This is Rick, how may I assist you today?",
    "thanks": "Sure thing! If you have any more questions, feel free to ask.",
    "farewell": "Goodbye! Have a great day!",
    "default": "I'm sorry, but I couldn't understand your question. Could you please rephrase it?",
    "chatbot-name": "This is Rick, an AI chatbot ready to help you",
     "location": '''We have multiple branches located accros the Australia. You can select as per your location: <a href= 'https://www.aghajuicetruganina.com.au/about-us'> Location <a>''',
    "book_table": "We do not book tables, but you can order from online or by phone number of specific store",
    "Nice" : "Nice to meet you too, how may I help you?",
    'want': 'You can make an order or contact our staff through our website',
    'popular': f'''Popular Dishes: 
our top rated milk shake and jucies

1. Mango milk shake 
                                           

2. Mixed fruit juice
                                            

3. Pistachio milk shake 
                                           


'''
    
}
   
    

query_engine = loaded_index.as_query_engine()

# Function to process user input and generate bot response
def process_user_input(user_input):
    if re.search(r'\b(hello|hi)\b', user_input.lower()):
        return custom_responses["greeting"]
    elif any(keyword in user_input.lower() for keyword in ['bye', 'goodbye', 'see you']):
        return custom_responses["farewell"]
    elif any(keyword in user_input.lower() for keyword in ['your name', 'who are you', 'who you are']):
        return custom_responses["chatbot-name"]
    elif any(keyword in user_input.lower() for keyword in ['which area', 'located', 'location', 'where is your']):
        return custom_responses["location"]
    elif any(keyword in user_input.lower() for keyword in ['thanks', 'thank you','alright']):
        return custom_responses["thanks"]
    elif any(keyword in user_input.lower() for keyword in ['book table', 'reservation','reserv', 'book']):
        return custom_responses["book_table"]
    elif any(keyword in user_input.lower() for keyword in ['yes i want', 'I want']):
        return custom_responses["want"]
    elif any(keyword in user_input.lower() for keyword in ['popular dishes']):
        return custom_responses["popular"]
   
    elif 'nice to meet' in user_input.lower():
        return custom_responses["Nice"]
    else:
        response = query_engine.query(user_input)
        if response:
            return response
        else:
            return custom_responses["default"]

if __name__ == '__main__':
    app.run(debug=True, port=2023)

What should be issue here and how can I solve it ?

My-CMDhub avatar Apr 26 '24 00:04 My-CMDhub