Skip to content
site logo mobile

Forum in maintenance, we will back soon 🙂

AI Chatbot on WordP...
 
Notifications
Clear all

AI Chatbot on WordPress in 5 Minutes doesn't work for me

22 Posts
4 Users
4 Likes
53 Views
(@bourbe)
Posts: 5
Active Member
Topic starter
 

Hello Hassan,

I followed your video to install AI chatbot in my web site but at the end I have an error

 

See here for the error in my website pls : https://kids.techubshop.com/

 

I dont see were the error can come from

Note : I am very very interesssed by augmenting this code by RAG and Agent. I already know how to implement this with this video where he built a bot combining RAG and Agent: https://youtu.be/Kn6k6ocEaK4

Please can you indicate me how to evolve the current code to reach this point pls ? I want to give to my ai bot a knowledge database with precises informations on my products 

 

Hereunder the current backend code:

function generate_chat_response( $last_prompt, $conversation_history ) {

// OpenAI API URL and key
$api_url = 'https://api.openai.com/v1/chat/completions';
$api_key = 'sk-sAkBfL2UTwt8FSxvQkwfT3BlbkFJD7LYpm9r.........'; // Replace with your actual API key

// Headers for the OpenAI API
$headers = [
    'Content-Type' => 'application/json',
    'Authorization' => 'Bearer ' . $api_key
];

// Add the last prompt to the conversation history
$conversation_history[] = [
    'role' => 'system',
    'content' => 'Answer questions only related to montessori pedagogical method, otherwise, say I dont know'
];

$conversation_history[] = [
    'role' => 'user',
    'content' => $last_prompt
];

// Body for the OpenAI API
$body = [
    'model' => 'gpt-3.5-turbo', // You can change the model if needed
    'messages' => $conversation_history,
    'temperature' => 0.7 // You can adjust this value based on desired creativity
];

// Args for the WordPress HTTP API
$args = [
    'method' => 'POST',
    'headers' => $headers,
    'body' => json_encode($body),
    'timeout' => 120
];

// Send the request
$response = wp_remote_request($api_url, $args);

// Handle the response
if (is_wp_error($response)) {
    return $response->get_error_message();
} else {
    $response_body = wp_remote_retrieve_body($response);
    $data = json_decode($response_body, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'success' => false,
            'message' => 'Invalid JSON in API response',
            'result' => ''
        ];
    } elseif (!isset($data['choices'])) {
        return [
            'success' => false,
            'message' => 'API request failed. Response: ' . $response_body,
            'result' => ''
        ];
    } else {
        $content = $data['choices'][0]['message']['content'];
        return [
            'success' => true,
            'message' => 'Response Generated',
            'result' => $content
        ];
    }
}
}

function generate_dummy_response( $last_prompt, $conversation_history ) {
// Dummy static response
$dummy_response = array(
    'success' => true,
    'message' => 'done',
    'result' => "here is my reply"
);

// Return the dummy response as an associative array
return $dummy_response;
}

function handle_chat_bot_request( WP_REST_Request $request ) {
$last_prompt = $request->get_param('last_prompt');
$conversation_history = $request->get_param('conversation_history');

$response = generate_chat_response($last_prompt, $conversation_history);
return $response;
}

function load_chat_bot_base_configuration(WP_REST_Request $request) {
// You can retrieve user data or other dynamic information here
$user_avatar_url = "https://kids.techubshop.com/wp-content/uploads/2024/04/businessman.png"; // Implement this function
$bot_image_url = "https://kids.techubshop.com/wp-content/uploads/2024/03/FLAVICONE.png"; // Implement this function

$response = array(
'botStatus' => 1,
'StartUpMessage' => "Hi, How are you?",
'fontSize' => '16',
'userAvatarURL' => $user_avatar_url,
'botImageURL' => $bot_image_url,
// Adding the new field
'commonButtons' => array(
    array(
        'buttonText' => 'I want your help!!!',
        'buttonPrompt' => 'I have a question about your courses'
    ),
    array(
        'buttonText' => 'I want a Discount',
        'buttonPrompt' => 'I want a discount'
    )

)

);

$response = new WP_REST_Response($response, 200);

return $response;
}

add_action( 'rest_api_init', function () {
register_rest_route( 'myapi/v1', '/chat-bot/', array(
   'methods' => 'POST',
   'callback' => 'handle_chat_bot_request',
   'permission_callback' => '__return_true'
) );

register_rest_route('myapi/v1', '/chat-bot-config', array(
    'methods' => 'GET',
    'callback' => 'load_chat_bot_base_configuration',
));
} );

Hereunder the current frontend code:

<!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://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" />
    <script src="https://unpkg.com/@dotlottie/player-component@latest/dist/dotlottie-player.mjs" type="module"></script>
    <script defer src="./script.js"></script>

    <title>Mini Chatbot</title>
</head>


<body>
    <div class="chatbot-container lwh-open-cbot">
        <div class="custom-chatbot__image" onclick="lwhOpenCbotToggleChat()">
            <dotlottie-player src="https://lottie.host/feefeb87-8206-4b50-8696-bda4747b4fdf/uUJIo0ICb6.json"
                background="transparent" speed="1" style="width: 80px; height: 80px;" loop autoplay></dotlottie-player>

        </div>
        <div class="custom-chatbot">

            <div class="chat">
                <div class="feedback-form">
                    <div class="feedback-header">
                        <p>Feedback</p>
                        <p class="feedback__modal-close" onclick="lwhOpenCbotremoveFeedbackModal()"><i class="fa-solid fa-xmark"></i></p>
                    </div>
                    <form onsubmit="lwhOpenCbotsendFeedback(event)">
                        <textarea name="feedback" id="feedback"  rows="4" required></textarea>
                        <button type="submit">Send Feedback</button>
                    </form>
                    
                </div>
                <div class="loading">
                    <p><i class="fa-solid fa-circle-notch fa-spin"></i></p>
                    <p>Wait a moment</p>
                </div>
                <div class="popup">
                    <p>Oops! Something went wrong!</h2>
                </div>
                <div class="chat__header">
                    <div>
                        <div class="chat__title"> AI Chatbot
                            
                        </div>
                        <div>
                            <div class="chat__status"><span></span> Offline</div>
                           
                        </div>
                    </div>
                    <div>
                

                        <div class="chat__close-icon" onclick="lwhOpenCbotToggleChat()">
                            <i class="fa-solid fa-xmark"></i>
                        </div>
                    </div>
                </div>

                <div class="chat__messages">
                   


                </div>


                <div class="chat__input-area">
                    <div class="selected-image-container">

                    </div>
                    <form id="messageForm" onsubmit="lwhOpenCbotonFormSubmit(event)">
                        <div>
                            <div class="input">


                                <div>
                                    <input type="text" id="message" name="message" placeholder="Type your message"
                                        autocomplete="off" required>
                                </div>

                            </div>
                            <div>
                                <button type="submit" id="submit-btn"><i class="fa-solid fa-paper-plane"></i></button>
                            </div>
                        </div>
                    </form>

                </div>


            </div>
        </div>
    </div>
</body>

</html>

 

<style>
.lwh-open-cbot, .lwh-open-cbot :root {
    --chatbot-width: 350px;
    --chatbot-font-family: 'Segoe UI';
    --chatbot-image-position-bottom: 5%;
    --chatbot-image-position-right: 3%;
    --chatbot-position-bottom: 6%;
    --chatbot-position-right: 10%;
    --chatbot-height:60vh;
    --chatbot-border-color: #E4E3E3;
    --chatbot-primary-color: #2B2A66;
    --chatbot-secondary-color: #2c2b8e;
    --chatbot-hover-color: #1e8ece;
    --chatbot-bg-color: #F1F1F1;
    --chatbot-scrollbar-track-color: #f3f3f3;
    --chatbot-scrollbar-thumb-color: #d7d7d7;
    --chatbot-scrollbar-thumb-hover-color: #949494;
    --chatbot-button-disabled-color: grey;
    --chatbot-popup-bg-color: #fff;
    --chatbot-dot-color: grey;
}

.lwh-open-cbot *,
.lwh-open-cbot *::after,
.lwh-open-cbot *::before,
.lwh-open-cbot *:focus {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

.lwh-open-cbot *:focus {
    box-shadow: none;
}


.lwh-open-cbot .custom-chatbot {
    width: var(--chatbot-width);
    font-family: var(--chatbot-font-family);
    position: fixed;
    bottom: var(--chatbot-position-bottom);
    right: var(--chatbot-position-right);
    overflow: hidden;
    z-index: 9998;
}

.lwh-open-cbot .custom-chatbot .chat__messages__ai a {
    color: var(--chatbot-primary-color);
    text-decoration: none;
}

.lwh-open-cbot .chat {
    background-color: white;
    position: relative;
    z-index: 9999;
    border: 1.5px solid var(--chatbot-border-color);
    border-radius: 12px;
    opacity: 0;
    transform: translateY(100%);
    transition: opacity 0.5s ease-in-out, transform 0.5s ease-in-out, display 0s linear 0.5s;
}

.lwh-open-cbot .chat.show {
    opacity: 1;
    transform: translateY(0);
    transition-delay: 0s;
}

.lwh-open-cbot .custom-chatbot__image {
    position: fixed;
    right: var(--chatbot-image-position-right);
    bottom: var(--chatbot-image-position-bottom);
    z-index: 9999;
    cursor: pointer;
}

.lwh-open-cbot .custom-chatbot button {
    border: none;
    background: none;
}

.lwh-open-cbot .custom-chatbot button>i {
    color: var(--chatbot-primary-color);
    font-size: 18px;
}

.lwh-open-cbot .custom-chatbot button:hover i {
    color: var(--chatbot-hover-color);
    cursor: pointer;
}

.lwh-open-cbot .custom-chatbot input[type='text'] {
    border: none;
    outline: none;
    padding: 0;
    box-shadow: none !important;
}

.lwh-open-cbot .chat__header {
    display: flex;
    justify-content: space-between;
    border-bottom: 1.5px solid var(--chatbot-border-color);
    padding: 12px 10px;
    align-items: flex-start;
    position: relative;
    z-index: 1;
}

.lwh-open-cbot .chat__header>div:nth-child(1)>div:nth-child(2) {
    display: flex;
    align-items: end;
    gap: 1rem;
    margin-top: 4px;
}

.lwh-open-cbot .chat__header .chat__new {
    font-size: 11px;
    font-weight: 500;
    padding: 3px 6px 4px 6px;
    background-color: var(--chatbot-primary-color);
    color: white;
    cursor: pointer;
    border-radius: 4px;
}

.lwh-open-cbot .chat__header .chat__new:hover {
    background-color: var(--chatbot-hover-color);
}

.lwh-open-cbot .chat__header>div:nth-child(2) {
    display: flex;
    gap: 0.5rem;
    align-items: center;
}

.lwh-open-cbot .chat__export i,
.lwh-open-cbot .chat__close-icon i {
    display: block;
}

.lwh-open-cbot .chat__export i:hover,
.lwh-open-cbot .chat__close-icon i:hover,
.lwh-open-cbot .copy-text i:hover,
.lwh-open-cbot .feedback-btn:hover,
.lwh-open-cbot .feedback__modal-close:hover {
    color: var(--chatbot-hover-color);
    cursor: pointer;
}

.lwh-open-cbot .chat__export {
    font-size: 12px;
    cursor: pointer;
    width: -moz-fit-content;
    width: fit-content;
    margin-left: -1px;
}

.lwh-open-cbot .chat__title {
    font-weight: 500;
    font-size: 18px;
}

.lwh-open-cbot .chat__title span {
    font-size: 12px;
}

.lwh-open-cbot .chat__status {
    font-size: 14px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.6);
    display: flex;
    gap: 6px;
    align-items: center;
    margin-top: 4px;
}

.lwh-open-cbot .chat__status span {
    background-color: #68D391;
    background-color: #acacac;
    width: 8px;
    height: 8px;
    display: block;
    border-radius: 100px;
}

.lwh-open-cbot .chat__close-icon {
    cursor: pointer;
    position: relative;
    z-index: 1;
}

.lwh-open-cbot .chat__messages {
    padding: 12px 10px 0 10px;
    display: flex;
    flex-direction: column;
    gap: 16px;
    height: var(--chatbot-height);
    overflow-y: auto;
    position: relative;
}

.lwh-open-cbot .chat__messages::-webkit-scrollbar,
.lwh-open-cbot .chat__messages__ai code::-webkit-scrollbar {
    width: 3px;
    height: 5px;
}

.lwh-open-cbot .chat__messages::-webkit-scrollbar-track,
.lwh-open-cbot .chat__messages__ai code::-webkit-scrollbar-track {
    background: var(--chatbot-scrollbar-track-color);
}

.lwh-open-cbot .chat__messages::-webkit-scrollbar-thumb,
.lwh-open-cbot .chat__messages__ai code::-webkit-scrollbar-thumb {
    background: var(--chatbot-scrollbar-thumb-color);
    border-radius: 100px;
}

.lwh-open-cbot .chat__messages::-webkit-scrollbar-thumb:hover,
.lwh-open-cbot .chat__messages__ai code::-webkit-scrollbar-thumb:hover {
    background: var(--chatbot-scrollbar-thumb-hover-color);
}

.lwh-open-cbot .chat__messages__user,
.lwh-open-cbot .chat__messages__ai {
    display: flex;
    gap: 6px;
    flex-direction: column;
    width: calc(100% - 38px);
}

.lwh-open-cbot .chat__messages__user {
    align-self: flex-end;
}

.lwh-open-cbot .chat__messages__user>div {
    align-items: end;
    align-self: flex-end;
}

.lwh-open-cbot .chat__messages__ai>div,
.lwh-open-cbot .chat__messages__user>div {
    display: flex;
    gap: 0.5rem;
}

.lwh-open-cbot .chat__messages__ai p {
    background-color: var(--chatbot-bg-color);
    padding: 6px 12px;
    border-radius: 0px 8px 8px 8px;
    width: -moz-fit-content;
    width: fit-content;
    align-self: flex-start;
    display: flex;
    justify-content: space-between;
    gap: 0.5rem;
    position: relative;
    padding-right: 20px;
}

.lwh-open-cbot .chat__messages__ai .code-snippet {
    background-color: rgb(27, 27, 27);
    border-radius: 8px;
}

.lwh-open-cbot .chat__messages__ai pre {
    display: flex;
    overflow: hidden;
}

.lwh-open-cbot .chat__messages__ai code {
    display: block;
    padding: 10px;
    font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
    color: #f8f8f8;
    overflow-x: auto;
    word-break: normal;
    word-spacing: normal;
    white-space: pre;
    align-self: flex-start;
    text-align: left;
}

.lwh-open-cbot .snippet-header {
    background: rgb(164, 164, 164);
    border-radius: 8px 8px 0 0;
    padding: 6px 12px;
}

.lwh-open-cbot .snippet-header button {
    cursor: pointer;
    color: rgb(55 55 55);
    font-weight: 600;
}

.lwh-open-cbot .chat__messages__ai img:not(.bot-image) {
    padding: 6px 12px;
    border-radius: 0px 8px 8px 8px;
    align-self: flex-start;
    border: 1.5px solid var(--chatbot-bg-color);
    max-width: 160px;
}

.lwh-open-cbot .chat__messages__user p {
    background-color: var(--chatbot-primary-color);
    padding: 6px 12px;
    border-radius: 8px 8px 0px 8px;
    color: white;
    width: -moz-fit-content;
    width: fit-content;
    align-self: flex-end;
}

.lwh-open-cbot .chat__messages__user img:not(.avatar-image) {
    padding: 6px 12px;
    border-radius: 8px 8px 0px 8px;
    align-self: flex-end;
    border: 1.5px solid var(--chatbot-primary-color);
    max-width: 160px;
}

.lwh-open-cbot .chat__input-area {
    padding: 12px 10px;
    position: relative;
    z-index: 1;
}

.lwh-open-cbot .chat__input-area>form {
    border: 2px solid var(--chatbot-border-color);
    border-radius: 10px;
    padding: 8px 10px;
}

.lwh-open-cbot .chat__input-area>form>div {
    display: flex;
    gap: 6px;
    align-items: center;
}

.lwh-open-cbot .chat__input-area .input {
    display: flex;
    gap: 6px;
    width: 100%;
    align-items: center;
}

.lwh-open-cbot .chat__input-area .input label {
    font-size: 12px;
    opacity: 0.7;
}

.lwh-open-cbot .chat__input-area .input label:hover {
    color: var(--chatbot-secondary-color);
    cursor: pointer;
    opacity: 1;
}

.lwh-open-cbot .chat__input-area .input>div:nth-child(1),
.lwh-open-cbot .chat__input-area .input input {
    width: 100%;
    font-size: 16px;
}

.lwh-open-cbot .custom-chatbot button[disabled] i {
    cursor: not-allowed;
    color: var(--chatbot-button-disabled-color);
}

.lwh-open-cbot .popup {
    display: none;
    width: 100%;
    position: absolute;
    background-color: var(--chatbot-popup-bg-color);
    padding: 12px;
    border-radius: 4px;
    top: 1%;
    opacity: 0;
    font-weight: 500;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    z-index: 2;
}

.lwh-open-cbot .popup-animation {
    animation: slideInRight 0.5s ease forwards, fadeOut 2s ease forwards 3s;
}

.lwh-open-cbot .popup p {
    color: var(--chatbot-popup-text-color);
}

.lwh-open-cbot .popup .close-btn {
    position: absolute;
    top: 5px;
    right: 5px;
    cursor: pointer;
}

@keyframes slideUp {
    from {
        transform: translateY(100%);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}

@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes fadeOut {
    from {
        opacity: 1;
    }
    to {
        opacity: 0;
    }
}

@keyframes blink {
    50% {
        fill: transparent;
    }
}

.lwh-open-cbot .dot {
    animation: 1s blink infinite;
    fill: var(--chatbot-dot-color);
}

.lwh-open-cbot .dot:nth-child(2) {
    animation-delay: 250ms;
}

.lwh-open-cbot .dot:nth-child(3) {
    animation-delay: 500ms;
}

.lwh-open-cbot .loading {
    position: absolute;
    top: 0;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-size: 20px;
}

.lwh-open-cbot .copy-text {
    cursor: pointer;
    font-size: 12px;
    position: absolute;
    top: 4px;
    right: 4px;
}

.lwh-open-cbot .copy-text span {
    display: none;
    position: absolute;
    background-color: white;
    border-radius: 4px;
    padding: 0px 6px 1px 6px;
    color: black;
    border: 1px solid var(--chatbot-border-color);
}

.lwh-open-cbot .avatar-image {
    display: block;
}

.lwh-open-cbot .startup-btns {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    position: absolute;
    bottom: 0;
}

.lwh-open-cbot .startup-btns p {
    padding: 6px 10px;
    border: 1px solid var(--chatbot-border-color);
    border-radius: 4px;
    width: -moz-fit-content;
    width: fit-content;
    cursor: pointer;
}

.lwh-open-cbot .startup-btns p:hover {
    background-color: var(--chatbot-hover-color);
    color: white;
}

.lwh-open-cbot .feedback-form {
    background: white;
    border-radius: 4px;
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
    position: absolute;
    width: 100%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1;
    padding: 0.8rem;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    display: none;
}

.lwh-open-cbot .feedback-form.show {
    display: flex;
}

.lwh-open-cbot .feedback-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 0 0 0.8rem 0;
}

.lwh-open-cbot .feedback-form form {
    display: flex;
    flex-direction: column;
    align-items: baseline;
}

.lwh-open-cbot .feedback-form textarea {
    width: 100%;
    border: 2px solid var(--chatbot-border-color);
    outline: none;
    padding: 6px;
    font-size: 16px;
}

.lwh-open-cbot .feedback-form button {
    background: var(--chatbot-primary-color);
    padding: 0.7rem;
    color: white;
    cursor: pointer;
    margin-top: 0.5rem;
    font-size: 14px;
    font-weight: 400;
}

.lwh-open-cbot .feedback-form button[disabled] {
    cursor: not-allowed;
    background-color: var(--chatbot-button-disabled-color) !important;
}

.lwh-open-cbot .feedback-form button:hover {
    background: var(--chatbot-hover-color);
}

.lwh-open-cbot .footer-area {
    padding: 0 10px 10px 10px;
    font-size: 11px;
    display: none;
}

.lwh-open-cbot .footer-area a {
    text-decoration: none;
}

@media (max-width: 679px) {
    .lwh-open-cbot .custom-chatbot {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        right: auto;
        bottom: auto;
    }
}
</style>

 

<script>
const apiUrl = 'https://kids.techubshop.com/wp-json/myapi/v1/chat-bot/';
const botConfigurationUrl = 'https://kids.techubshop.com/wp-json/myapi/v1/chat-bot-config';
const copyButtons = document.querySelectorAll('.lwh-open-cbot .copy-button');
const button = document.querySelector('.lwh-open-cbot #submit-btn');
let messageInput = document.querySelector('.lwh-open-cbot #message');
let content = [];
let botConfigData = '';
let conversationTranscript = [];

function lwhOpenCbotToggleChat() {
    const chatWindow = document.querySelector(".lwh-open-cbot .chat");
    chatWindow.classList.toggle('show');
    if(chatWindow.classList.contains('show')){
        document.querySelector(".lwh-open-cbot .custom-chatbot").style.zIndex = '9999'
    }
    else{
        document.querySelector(".lwh-open-cbot .custom-chatbot").style.zIndex = '9998'
    }
}

function lwhOpenCbotonFormSubmit(event, userMessage) {
    event.preventDefault();
    if(button.disabled == true) return
    let message;
    if(userMessage == undefined){
        message = messageInput.value.trim();
        document.querySelector(".lwh-open-cbot .startup-btns").style.display = "none";
    }
    else{
        message = userMessage;
    }
    content.push({
        role: 'user',
        message: message,
    });
    let timestamp = new Date().toLocaleString();
    conversationTranscript.push({
        sender: 'user',
        time: timestamp,
        message: message,
    });
    data = "";
    if (message !== '') {
        lwhOpenCbotaddMessage('user', message);
        messageInput.value = '';
        lwhOpenCbotaddTypingAnimation('ai');
        lwhOpenCbotfetchData()
    }
}

function lwhOpenCbotaddMessage(sender, message) {
    let chatMessagesContainer = document.querySelector('.lwh-open-cbot .chat__messages');
    let messageContainer = document.createElement('div');
    messageContainer.classList.add('chat__messages__' + sender);
    let messageDiv = document.createElement('div');
    messageDiv.innerHTML = `
            ${sender === 'ai' ?
            `
                <div>
                <img width="30px" class="bot-image"
                    src="${botConfigData.botImageURL}"
                    alt="bot-image">
                </div>
                `
            : ""
        }
            <p>${message}
             </p>
            ${sender === 'user' ?
            `
                <div>
                <img width="30px" class="avatar-image"
                    src="${botConfigData.userAvatarURL}"
                    alt="avatar">
                </div>
                `
            : ""
        }
        `;
    messageContainer.appendChild(messageDiv);
    chatMessagesContainer.appendChild(messageContainer);
    chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
}

function lwhOpenCbotaddTypingAnimation(sender) {
    let chatMessagesContainer = document.querySelector('.lwh-open-cbot .chat__messages');
    let typingContainer = document.createElement('div');
    typingContainer.classList.add('chat__messages__' + sender);
    let typingAnimationDiv = document.createElement('div');
    typingAnimationDiv.classList.add('typing-animation');
    typingAnimationDiv.innerHTML = `
        <div>
        <img width="30px" class="bot-image"
            src="${botConfigData.botImageURL}"
            alt="">
        </div>
  <p>
  <svg height="16" width="40" style="max-height: 20px;">
    <circle class="dot" cx="10" cy="8" r="3" style="fill:grey;" />
    <circle class="dot" cx="20" cy="8" r="3" style="fill:grey;" />
    <circle class="dot" cx="30" cy="8" r="3" style="fill:grey;" />
  </svg>
</p>
  `;
    typingContainer.appendChild(typingAnimationDiv);
    chatMessagesContainer.appendChild(typingContainer);
    chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
}

function lwhOpenCbotreplaceTypingAnimationWithMessage(sender, message) {
    let chatMessagesContainer = document.querySelector('.lwh-open-cbot .chat__messages');
    let typingContainer = document.querySelector('.lwh-open-cbot .chat__messages__' + sender + ':last-child');
    if (typingContainer) {
        let messageContainer = document.createElement('div');
        messageContainer.classList.add('chat__messages__' + sender);
        messageContainer.classList.add('chat_messages_ai');
        let messageDiv = document.createElement('div');
        messageDiv.innerHTML = `
                ${sender === 'ai' ?
                `
                    <div>
                    <img width="30px" class="bot-image"
                        src="${botConfigData.botImageURL}"
                        alt="bot-image">
                    </div>
                    `
                : ""
            }
                <p class="typing-effect"></p>
                ${sender === 'user' ?
                `
                    <div>
                    <img width="30px" class="avatar-image"
                        src="${botConfigData.userAvatarURL}"
                        alt="avatar">
                    </div>
                    `
                : ""
            }
            `;
        messageContainer.appendChild(messageDiv);
        typingContainer.parentNode.replaceChild(messageContainer, typingContainer);
        const typingEffectElement = messageDiv.querySelector(".typing-effect");
        let index = 0;
        const typingInterval = setInterval(() => {
            typingEffectElement.textContent += message[index];
            index++;
            if (index === message.length) {
                clearInterval(typingInterval);
                typingEffectElement.insertAdjacentHTML('beforeend', `<span title="copy" class="copy-text" onclick="lwhOpenCbotcopyText(event)"><i class="fa-regular fa-copy"></i><span>copied</span></span>`);
                chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
            }
        }, 5);
        chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
    }
}

function lwhOpenCbotremoveTypingAnimation() {
    let typingAnimationDivs = document.querySelectorAll('.lwh-open-cbot .typing-animation');
    typingAnimationDivs.forEach(function (typingAnimationDiv) {
        let chatMessagesAiDiv = typingAnimationDiv.closest('.chat__messages__ai');
        if (chatMessagesAiDiv) {
            chatMessagesAiDiv.parentNode.removeChild(chatMessagesAiDiv);
        }
    });
}

copyButtons.forEach(button => {
    button.addEventListener('click', function (event) {
        const codeElement = this.parentNode.nextElementSibling.querySelector('code');
        const codeText = codeElement.textContent;
        navigator.clipboard.writeText(codeText).then(function () {
            event.target.innerText = "Copied";
            setTimeout(() => {
                event.target.innerText = "Copy";
            }, 2000);
        }).catch(function (error) {
            console.error('Error copying code: ', error);
        });
    });
});

function lwhOpenCbotcopyText(event) {
    const paragraph = event.target.closest('p');
    const clone = paragraph.cloneNode(true);
    clone.querySelectorAll('.copy-text').forEach(elem => {
        elem.parentNode.removeChild(elem);
    });
    const textToCopy = clone.textContent.trim();
    navigator.clipboard.writeText(textToCopy)
        .then(() => {
            const copiedSpan = event.target.nextElementSibling;
            copiedSpan.style.display = 'block';
            setTimeout(() => {
                copiedSpan.style.display = 'none';
            }, 2000);
        })
        .catch(error => {
            console.error('Error copying text: ', error);
        });
}

async function lwhOpenCbotfetchData() {
    button.disabled = true;
    try {
        response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                "last_prompt": content[content.length - 1].message,
                "conversation_history": content.map(item => ({
                    "role": item.role,
                    "content": item.message
                }))
            })
        });
        if (response.ok) {
            data = await response.json();
            console.log(data, "Data from api");
            button.disabled = false;
            if (!data.success) {
                lwhOpenCbotremoveTypingAnimation()
                lwhOpenCbotshowPopup('Oops! Something went wrong!', '#991a1a');
                throw new Error("Something went wrong. Please Try Again!");
            }
        } else {
            lwhOpenCbotshowPopup('Oops! Something went wrong!', '#991a1a');
            throw new Error("Request failed. Please try again!");
        }
        content.push({
            role: 'assistant',
            message: data.result,
        });
        let timestamp = new Date().toLocaleString();
        conversationTranscript.push({
            sender: 'bot',
            time: timestamp,
            message: data.result,
        });
        lwhOpenCbotreplaceTypingAnimationWithMessage('ai', data.result);
    } catch (error) {
        lwhOpenCbotremoveTypingAnimation();
        lwhOpenCbotshowPopup('Oops! Something went wrong!', '#991a1a');
        console.error('There was a problem with the fetch operation:', error);
        return;
    }
}

async function lwhOpenCbotfetchBotConfiguration() {
    const chatMessagesContainer = document.querySelector(".lwh-open-cbot .chat__messages");
    document.querySelector(".lwh-open-cbot .loading").style.display = 'flex';
    chatMessagesContainer.innerHTML = '';
    let startupBtnsDiv = document.createElement('div');
    startupBtnsDiv.classList.add('startup-btns');
    chatMessagesContainer.appendChild(startupBtnsDiv);
    let botResponse = ''
    try {
        botResponse = await fetch(botConfigurationUrl);
        if (botResponse.ok) {
            botConfigData = await botResponse.json();
            console.log(botConfigData, "Data from api");
            chatMessagesContainer.style.fontSize = `${botConfigData.fontSize}px`;
            let startupBtns=''
            const startupBtnContainer = document.querySelector('.lwh-open-cbot .startup-btns');
            botConfigData.commonButtons.forEach(btn => {
                startupBtns += `<p onclick="lwhOpenCbotonFormSubmit(event, '${btn.buttonPrompt}'); lwhOpenCbothandleStartupBtnClick(event);">${btn.buttonText}</p>`;
            });            
            startupBtnContainer.innerHTML = startupBtns;
            if (botConfigData.botStatus == 1) {
                document.querySelector(".lwh-open-cbot .chat__status").innerHTML = `<span></span> Online`;
                document.querySelector(".lwh-open-cbot .chat__status").querySelector("span").style.background = "#68D391";
            }
           
            document.querySelector(".lwh-open-cbot .loading").style.display = 'none';
            lwhOpenCbotaddMessage('ai', botConfigData.StartUpMessage);
            content.push({
                role: 'assistant',
                message: botConfigData.StartUpMessage,
            });
            let timestamp = new Date().toLocaleString();
            conversationTranscript.push({
                sender: 'bot',
                time: timestamp,
                message: botConfigData.StartUpMessage,
            });
        } else {
            document.querySelector(".lwh-open-cbot .loading").style.display = 'none';
            lwhOpenCbotshowPopup('Oops! Something went wrong!', '#991a1a');
            throw new Error("Request failed. Please try again!");
        }
    } catch (error) {
        lwhOpenCbotshowPopup('Oops! Something went wrong!', '#991a1a');
        button.disabled = true
        console.error('There was a problem with the fetch operation:', error);
        return;
    }
}

function lwhOpenCbotshowPopup(val, color) {
    button.disabled = false;
    const popup = document.querySelector('.lwh-open-cbot .popup');
    popup.style.display = 'block';
    popup.style.opacity = 1;
    const innerPopup = popup.querySelector('p');
    innerPopup.innerText = val;
    innerPopup.style.color = color;
    popup.classList.add('popup-animation');
    setTimeout(() => {
        popup.classList.remove('popup-animation');
        popup.style.display = 'none';
        popup.style.opacity = 0;
    }, 3000);
}


function lwhOpenCbothandleStartupBtnClick(event){
    const startupBtnContainer = event.target.parentNode;
    startupBtnContainer.style.display = 'none';
}

lwhOpenCbotfetchBotConfiguration();

</script>

 

 

 

 

 

 

 

 
Posted : 04/27/2024 10:13 pm
(@bourbe)
Posts: 5
Active Member
Topic starter
 

Hello

I found my error and the ai bot work very well now

 

The problem was that I put the wrong OPENAI API KEY 

 

Please can you help me help to evolve this AI Chatbot by augmenting this code by RAG and Agent. I already know how to implement this with this video where he built a bot combining RAG and Agent:  https://youtu.be/Kn6k6ocEaK4

Please can you indicate me how to evolve the current code to reach this point pls ? I want to give to my ai bot a knowledge database with precises informations on my products  and function to operate some task

 

 
Posted : 04/28/2024 12:36 am
Hasan Aboul Hasan
(@admin)
Posts: 976
Member Admin
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
 

@bourbe I am working on this tutorial.

 
Posted : 04/28/2024 10:04 am
(@bourbe)
Posts: 5
Active Member
Topic starter
 

Hello Hassan

Thank you very much

 
Posted : 04/28/2024 3:39 pm
(@google-techbiason)
Posts: 9
Active Member
 

My chatbot is still not working. Please help me to fix it @admin 

 

 
Posted : 05/04/2024 6:46 am
Hasan Aboul Hasan
(@admin)
Posts: 976
Member Admin
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
 

@google-techbiason, what is the problem?

 
Posted : 05/04/2024 7:17 am
(@google-techbiason)
Posts: 9
Active Member
 

Opps!! Something went wrong.

And it is also showing offline status rather than online. Please help @admin 

 
Posted : 05/04/2024 10:03 am
(@google-techbiason)
Posts: 9
Active Member
 
Screenshot 2024 05 04 at 3.34.53 PM

Here are the proofs

 
Posted : 05/04/2024 10:05 am
(@google-techbiason)
Posts: 9
Active Member
 

please help @admin 

 
Posted : 05/04/2024 10:34 am
SSAdvisor
(@ssadvisor)
Posts: 945
Noble Member
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
 

@google-techbiason what is your URL for the problematic chatbot? Did you make sure to change any URL within the code to your own? Did you make sure to use your own API keys if there are any?

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 05/04/2024 11:51 am
(@google-techbiason)
Posts: 9
Active Member
 

@ssadvisor Yes I did all the steps 

 

 
Posted : 05/04/2024 12:27 pm
SSAdvisor
(@ssadvisor)
Posts: 945
Noble Member
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
 

@google-techbiason and the URL?

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 05/04/2024 8:06 pm
Hasan Aboul Hasan
(@admin)
Posts: 976
Member Admin
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
 

@google-techbiason did you follow up the guide step by step, openAI key? changed the URLs? can you share a screenshot of the URLs you changed

 
Posted : 05/05/2024 12:46 pm
(@google-techbiason)
Posts: 9
Active Member
 

Here is the links @admin @ssadvisor https://200wordessay.com/chatbot/

 
Posted : 05/05/2024 1:43 pm
SSAdvisor
(@ssadvisor)
Posts: 945
Noble Member
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
 

@google-techbiason you need to resolve these errors:

image

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 05/05/2024 1:55 pm
(@google-techbiason)
Posts: 9
Active Member
 

can you please help me with the same

 

 

 
Posted : 05/05/2024 3:37 pm
(@google-techbiason)
Posts: 9
Active Member
 

to provide me the exact codes

 

 
Posted : 05/05/2024 3:38 pm
SSAdvisor
(@ssadvisor)
Posts: 945
Noble Member
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
 

@google-techbiason based on the source code I've inspected you've inserted the CSS and JavaScript more than once and this is causing the error.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 05/05/2024 11:06 pm
Hasan Aboul Hasan
(@admin)
Posts: 976
Member Admin
Premium Member
Pythonista Prodigy Badge
Prompt Engineer
API Entrepreneur
Power Member
 

@google-techbiason I see this error:

"API request failed. Response: {
    "error": {
        "message": "You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs:  https://platform.openai.com/docs/guides/error-codes/api-errors .",
        "type": "insufficient_quota",
        "param": null,
        "code": "insufficient_quota"
    }
}
"

check OpenAI Account, you need credits probably

 
Posted : 05/06/2024 7:28 am
SSAdvisor reacted
(@google-techbiason)
Posts: 9
Active Member
 

ok

 
Posted : 05/06/2024 10:04 am
Page 1 / 2
Share: