Below, you’ll find a detailed guide on how to add the Ai Engine Shortcodes to your WordPress website, including their parameters, examples, and PHP function code. Additionally, we’ll assist you with common issues that might cause the Ai Engine Plugin shortcodes not to show or not to work correctly.
Before starting, here is an overview of the Ai Engine Plugin and the shortcodes it provides:

"AI Engine is a dynamic WordPress plugin that integrates chatbots, content generators, virtual assistants, and cutting-edge GPT 4 technology. It elevates website interaction and user engagement."
- [mwai_chatbot_v2]
- [mwai_discussions]
- [mwai_chat]
- [mwai_imagesbot]
AI Engine [mwai_chatbot_v2] Shortcode
The MWAI Chatbot V2 shortcode is designed to integrate an AI chatbot into your WordPress site. It allows users to customize chatbot parameters, resolve bot info, and handle both server and client-side operations. The shortcode applies filters to chatbot parameters, resolves bot info such as botId and customId, and handles errors. It also converts atts keys into camelCase to match the internal params system. It further prepares server parameters and front parameters, cleans these parameters, and sets transient for server-side operations. For client-side, it prepares JSON for front params, system params, and theme. To use it, simply add [mwai_chatbot_v2] to your post or page.
Shortcode: [mwai_chatbot_v2]
Parameters
Here is a list of all possible mwai_chatbot_v2 shortcode parameters and attributes:
chatbot
– specifies the chatbot to be usedbotId
– unique identifier of the chatbotcustomId
– custom identifier for the chatbotlocalMemory
– enables or disables local memory of chatbotthemeId
– identifier for the theme to be applied to the chatbot
Examples and Usage
Basic example – Display a chatbot on your page using the ‘mwai_chatbot_v2’ shortcode without any parameters
[mwai_chatbot_v2 /]
Advanced examples
Customize the chatbot by using the ‘themeId’ parameter. This allows you to apply a specific theme to the chatbot. Replace ‘themeId’ with your desired theme ID.
[mwai_chatbot_v2 themeId=1 /]
Use the ‘localMemory’ parameter to enable or disable local memory for the chatbot. This allows the chatbot to remember the previous conversation with a user. Replace ‘true’ with ‘false’ to disable this feature.
[mwai_chatbot_v2 localMemory=true /]
Combine multiple parameters to fully customize the chatbot. In this example, we’re applying a specific theme and enabling local memory.
[mwai_chatbot_v2 themeId=1 localMemory=true /]
PHP Function Code
In case you have difficulties debugging what causing issues with [mwai_chatbot_v2]
shortcode, check below the related PHP functions code.
Shortcode line:
add_shortcode( 'mwai_chatbot_v2', array( $this, 'chat_shortcode' ) );
Shortcode PHP function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | function chat_shortcode( $atts ) { $atts = empty ( $atts ) ? [] : $atts ; // Let the user override the chatbot params $atts = apply_filters( 'mwai_chatbot_params' , $atts ); // Resolve the bot info $resolvedBot = $this ->resolveBotInfo( $atts , 'chatbot' ); if ( isset( $resolvedBot [ 'error' ] ) ) { return $resolvedBot [ 'error' ]; } $chatbot = $resolvedBot [ 'chatbot' ]; $botId = $resolvedBot [ 'botId' ]; $customId = $resolvedBot [ 'customId' ]; // Rename the keys of the atts into camelCase to match the internal params system. $atts = array_map ( function ( $key , $value ) { $key = str_replace ( '_' , ' ' , $key ); $key = ucwords( $key ); $key = str_replace ( ' ' , '' , $key ); $key = lcfirst( $key ); return [ $key => $value ]; }, array_keys ( $atts ), $atts ); $atts = array_merge ( ... $atts ); $frontParams = []; foreach ( MWAI_CHATBOT_FRONT_PARAMS as $param ) { if ( isset( $atts [ $param ] ) ) { if ( $param === 'localMemory' ) { $frontParams [ $param ] = $atts [ $param ] === 'true' ; } else { $frontParams [ $param ] = $atts [ $param ]; } } else if ( isset( $chatbot [ $param ] ) ) { $frontParams [ $param ] = $chatbot [ $param ]; } } // Server Params $serverParams = []; foreach ( MWAI_CHATBOT_SERVER_PARAMS as $param ) { if ( isset( $atts [ $param ] ) ) { $serverParams [ $param ] = $atts [ $param ]; } } // Front Params $frontSystem = $this ->build_front_params( $botId , $customId ); // Clean Params $frontParams = $this ->cleanParams( $frontParams ); $frontSystem = $this ->cleanParams( $frontSystem ); $serverParams = $this ->cleanParams( $serverParams ); // Server-side: Keep the System Params if ( count ( $serverParams ) > 0 ) { if ( empty ( $customId ) ) { $customId = md5( json_encode( $serverParams ) ); $frontSystem [ 'customId' ] = $customId ; } set_transient( 'mwai_custom_chatbot_' . $customId , $serverParams , 60 * 60 * 24 ); } // Client-side: Prepare JSON for Front Params and System Params $theme = isset( $frontParams [ 'themeId' ] ) ? $this ->core->getTheme( $frontParams [ 'themeId' ] ) : null; $jsonFrontParams = htmlspecialchars( json_encode( $frontParams ), ENT_QUOTES, 'UTF-8' ); $jsonFrontSystem = htmlspecialchars( json_encode( $frontSystem ), ENT_QUOTES, 'UTF-8' ); $jsonFrontTheme = htmlspecialchars( json_encode( $theme ), ENT_QUOTES, 'UTF-8' ); //$jsonAttributes = htmlspecialchars(json_encode($atts), ENT_QUOTES, 'UTF-8'); $this ->enqueue_scripts(); return "<div class='mwai-chatbot-container' data-params='{$jsonFrontParams}' data-system='{$jsonFrontSystem}' data-theme='{$jsonFrontTheme}'></div>" ; } |
Code file location:
ai-engine/ai-engine/classes/modules/chatbot.php
AI Engine [mwai_discussions] Shortcode
The ‘mwai_discussions’ shortcode is a function in the AI-engine plugin that generates a chatbot interface. It resolves bot info, prepares parameters, and builds a chatbot container. This function takes attributes, converts them to camelCase, and merges them. It then sets front and server parameters. The function also cleans up these parameters, retrieves the theme, and encodes them into JSON format. Finally, it returns a div container with the chatbot interface, including the parameters, system, and theme data.
Shortcode: [mwai_discussions]
Parameters
Here is a list of all possible mwai_discussions shortcode parameters and attributes:
botId
– Identifies the specific bot being usedcustomId
– Custom identifier for additional bot customizationthemeId
– Specifies the theme used for displaying the chatbotMWAI_DISCUSSIONS_FRONT_PARAMS
– Parameters for front-end configurationMWAI_DISCUSSIONS_SERVER_PARAMS
– Parameters for server-side configuration
Examples and Usage
Basic example – Displaying a chat discussion using the default bot parameters
[mwai_discussions /]
Advanced examples:
Displaying a chat discussion with custom parameters. In this case, we’re specifying a custom bot ID and theme ID for the chat discussion.
[mwai_discussions bot_id="123" theme_id="456" /]
Using the shortcode to display a chat discussion with a specific custom ID and setting a custom parameter (e.g., ‘param1’).
[mwai_discussions custom_id="789" param1="value1" /]
Using the shortcode to display a chat discussion with multiple custom parameters. The parameters ‘param1’, ‘param2’, and ‘param3’ are set to ‘value1’, ‘value2’, and ‘value3’, respectively.
[mwai_discussions param1="value1" param2="value2" param3="value3" /]
Using the shortcode to display a chat discussion with a custom bot ID, custom ID, and theme ID, along with multiple custom parameters.
[mwai_discussions bot_id="123" custom_id="789" theme_id="456" param1="value1" param2="value2" param3="value3" /]
PHP Function Code
In case you have difficulties debugging what causing issues with [mwai_discussions]
shortcode, check below the related PHP functions code.
Shortcode line:
add_shortcode( 'mwai_discussions', [ $this, 'shortcode_chat_discussions' ] );
Shortcode PHP function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | function shortcode_chat_discussions( $atts ) { $atts = empty ( $atts ) ? [] : $atts ; // Resolve the bot info $resolvedBot = $this ->resolveBotInfo( $atts ); if ( isset( $resolvedBot [ 'error' ] ) ) { return $resolvedBot [ 'error' ]; } $chatbot = $resolvedBot [ 'chatbot' ]; $botId = $resolvedBot [ 'botId' ]; $customId = $resolvedBot [ 'customId' ]; // Rename the keys of the atts into camelCase to match the internal params system. $atts = array_map ( function ( $key , $value ) { $key = str_replace ( '_' , ' ' , $key ); $key = ucwords( $key ); $key = str_replace ( ' ' , '' , $key ); $key = lcfirst( $key ); return [ $key => $value ]; }, array_keys ( $atts ), $atts ); $atts = array_merge ( ... $atts ); // Front Params $frontParams = []; foreach ( MWAI_DISCUSSIONS_FRONT_PARAMS as $param ) { if ( isset( $atts [ $param ] ) ) { $frontParams [ $param ] = $atts [ $param ]; } else if ( isset( $chatbot [ $param ] ) ) { $frontParams [ $param ] = $chatbot [ $param ]; } } // Server Params $serverParams = []; foreach ( MWAI_DISCUSSIONS_SERVER_PARAMS as $param ) { if ( isset( $atts [ $param ] ) ) { $serverParams [ $param ] = $atts [ $param ]; } } // Front System $frontSystem = $this ->build_front_params( $botId , $customId ); // Clean Params $frontParams = $this ->cleanParams( $frontParams ); $frontSystem = $this ->cleanParams( $frontSystem ); $serverParams = $this ->cleanParams( $serverParams ); $theme = isset( $frontParams [ 'themeId' ] ) ? $this ->core->getTheme( $frontParams [ 'themeId' ] ) : null; $jsonFrontParams = htmlspecialchars( json_encode( $frontParams ), ENT_QUOTES, 'UTF-8' ); $jsonFrontSystem = htmlspecialchars( json_encode( $frontSystem ), ENT_QUOTES, 'UTF-8' ); $jsonFrontTheme = htmlspecialchars( json_encode( $theme ), ENT_QUOTES, 'UTF-8' ); return "<div class='mwai-discussions-container' data-params='{$jsonFrontParams}' data-system='{$jsonFrontSystem}' data-theme='{$jsonFrontTheme}'></div>" ; } |
Code file location:
ai-engine/ai-engine/classes/modules/chatbot.php
AI Engine [mwai_chat] Shortcode
The ‘mwai_chat’ shortcode is used to integrate a chatbot in a WordPress website. It creates a chat interface where users can interact with the AI. It handles various parameters like user and AI names, chat context, and UI parameters like text input placeholder and compliance text. It also manages chatbot system parameters like session IDs and OpenAI parameters like model and temperature. This shortcode is highly customizable and adaptable to various chatbot needs.
Shortcode: [mwai_chat]
Parameters
Here is a list of all possible mwai_chat shortcode parameters and attributes:
ai_name
– Specifies the name of the AI bot.user_name
– Sets the name of the user in the chat.guest_name
– Defines the name for a guest user.sys_name
– Sets the system name in the chat.context
– Sets the context for the chat conversation.text_send
– Customizes the text for the send button.text_clear
– Customizes the text for the clear button.text_input_maxlength
– Defines the maximum length of the text input.text_input_placeholder
– Sets the placeholder text for the input field.text_compliance
– Sets the compliance text for the chatbot.start_sentence
– Defines the starting sentence for the chatbot.window
– Determines if the chatbot appears in a separate window.copy_button
– Enables or disables the copy button in the chat.fullscreen
– Enables or disables fullscreen mode for the chat window.icon
– Sets a custom icon for the chatbot.icon_text
– Sets the text for the chatbot’s icon.icon_alt
– Sets the alt text for the chatbot’s icon.icon_position
– Determines the position of the chatbot’s icon.style
– Sets the style for the chatbot interface.id
– Unique identifier for the chatbot.mode
– Sets the mode of operation for the chatbot.max_results
– Sets the maximum number of results to display from the chatbot.max_messages
– Sets the maximum number of messages to display in the chat.casually_fine_tuned
– Toggles the casually fine-tuned mode.embeddings_index
– Sets the embeddings index for the chatbot.prompt_ending
– Sets the ending prompt for the chatbot.completion_ending
– Sets the ending completion for the chatbot.model
– Sets the AI model used by the chatbot.temperature
– Sets the temperature for the AI model.max_tokens
– Sets the maximum number of tokens for the AI model.service
– Defines the service used by the chatbot.api_key
– Sets the API key for the chatbot service.
Examples and Usage
Basic example – Displaying a chatbot on your website.
[mwai_chat]
Advanced examples
Displaying a chatbot with a specific AI name, user name and guest name. The AI name is the name that will be displayed for the AI in the chat interface, the user name is the name that will be displayed for the user in the chat interface, and the guest name is the name that will be used when the user has not specified a name.
[mwai_chat ai_name="Chatbot" user_name="User" guest_name="Guest"]
Displaying a chatbot with a specific context. The context is a string that will be added at the beginning of the conversation to provide some context to the AI.
[mwai_chat context="Welcome to our website. How can we assist you today?"]
Displaying a chatbot with a specific starting sentence. The starting sentence is the first sentence that the AI will say when the chat is opened.
[mwai_chat start_sentence="Hello, how can I assist you today?"]
Displaying a chatbot with a specific text for the send button and the clear button. The text_send is the text that will be displayed on the send button, and the text_clear is the text that will be displayed on the clear button.
[mwai_chat text_send="Send" text_clear="Clear"]
Displaying a chatbot with a specific maximum length for the input text. The text_input_maxlength is the maximum number of characters that the user can input in the chat.
[mwai_chat text_input_maxlength="200"]
Displaying a chatbot with a specific placeholder for the input text. The text_input_placeholder is the text that will be displayed in the input field when it is empty.
[mwai_chat text_input_placeholder="Type your message here..."]
Displaying a chatbot with a specific compliance text. The text_compliance is the text that will be displayed to inform the user about any compliance or legal information related to the chat.
[mwai_chat text_compliance="Your conversation will be stored for quality and training purposes."]
PHP Function Code
In case you have difficulties debugging what causing issues with [mwai_chat]
shortcode, check below the related PHP functions code.
Shortcode line:
add_shortcode( 'mwai_chat', array( $this, 'chat' ) );
Shortcode PHP function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 | function chat( $atts ) { $this ->usingChat = true; // Use the core default parameters, or the user default parameters $override = $this ->core->get_option( 'shortcode_chat_params_override' ); $defaults_params = $override ? $this ->core->get_option( 'shortcode_chat_params' ) : $this ->core->get_option( 'shortcode_chat_default_params' ); // Give a chance to modify the default parameters one last time $defaults = apply_filters( 'mwai_chatbot_params_defaults' , $defaults_params ); // Make sure all the mandatory params are set foreach ( $this ->core->defaultChatbotParams as $key => $value ) { if ( !isset( $defaults [ $key ] ) ) { $defaults [ $key ] = $value ; } } // Override with the shortcode, and before/after filters //$atts = apply_filters( 'mwai_chatbot_params_before', $atts ); $atts = shortcode_atts( $defaults , $atts ); //$atts = apply_filters( 'mwai_chatbot_params', $atts ); // UI Parameters $aiName = addslashes ( trim( $atts [ 'ai_name' ] ) ); $userName = addslashes ( trim( $atts [ 'user_name' ] ) ); $guestName = addslashes ( trim( $atts [ 'guest_name' ] ) ); $sysName = addslashes ( trim( $atts [ 'sys_name' ] ) ); $context = addslashes ( $atts [ 'context' ] ); $context = preg_replace( '/\n/' , "\\n" , $context ); $textSend = addslashes ( trim( $atts [ 'text_send' ] ) ); $textClear = addslashes ( trim( $atts [ 'text_clear' ] ) ); $textInputMaxLength = intval ( $atts [ 'text_input_maxlength' ] ); $textInputPlaceholder = addslashes ( trim( $atts [ 'text_input_placeholder' ] ) ); $textCompliance = ( trim( $atts [ 'text_compliance' ] ) ); $startSentence = addslashes ( trim( $atts [ 'start_sentence' ] ) ); $window = filter_var( $atts [ 'window' ], FILTER_VALIDATE_BOOLEAN ); $copyButton = filter_var( $atts [ 'copy_button' ], FILTER_VALIDATE_BOOLEAN ); $fullscreen = filter_var( $atts [ 'fullscreen' ], FILTER_VALIDATE_BOOLEAN ); $icon = isset( $atts [ 'icon' ] ) ? addslashes ( trim( $atts [ 'icon' ] ) ) : '' ; $iconText = trim( $atts [ 'icon_text' ] ); $iconAlt = addslashes ( trim( $atts [ 'icon_alt' ] ) ); $iconPosition = addslashes ( trim( $atts [ 'icon_position' ] ) ); $style = $atts [ 'style' ]; // Validade & Enhance UI Parameters $aiName = $this ->formatAiName( $aiName ); $userName = $this ->formatUserName( $userName , $guestName ); $rawAiName = $this ->formatRawName( $aiName ); $rawUserName = $this ->formatRawUserName( $userName , $guestName ); // Chatbot System Parameters $id = empty ( $atts [ 'id' ] ) ? uniqid() : $atts [ 'id' ]; $typewriter = $this ->core->get_option( 'shortcode_chat_typewriter' ); $memorizeChat = ! empty ( $atts [ 'id' ] ); $id = preg_replace( '/[^a-zA-Z0-9]/' , '' , $id ); $env = $atts [ 'env' ]; $mode = $atts [ 'mode' ]; $maxResults = $mode === 'chat' ? 1 : $atts [ 'max_results' ]; $maxSentences = ! empty ( $atts [ 'max_messages' ] ) ? intval ( $atts [ 'max_messages' ] ) : 1; $sessionId = $this ->core->get_session_id(); $rest_nonce = wp_create_nonce( 'wp_rest' ); $casuallyFineTuned = boolval( $atts [ 'casually_fine_tuned' ] ); $embeddingsIndex = $atts [ 'embeddings_index' ]; $promptEnding = addslashes ( trim( $atts [ 'prompt_ending' ] ) ); $completionEnding = addslashes ( trim( $atts [ 'completion_ending' ] ) ); if ( $casuallyFineTuned ) { $promptEnding = "\\n\\n###\\n\\n" ; $completionEnding = "\\n\\n" ; } $debugMode = $this ->core->get_option( 'debug_mode' ); // OpenAI Parameters $model = $atts [ 'model' ]; $temperature = $atts [ 'temperature' ]; $maxTokens = $atts [ 'max_tokens' ]; $service = $atts [ 'service' ]; $apiKey = $atts [ 'api_key' ]; // Variables $apiUrl = get_rest_url( null, $mode === 'images' ? 'ai-chatbot/v1/imagesbot' : 'ai-chatbot/v1/chat' ); $baseClasses = 'mwai-chat' ; $baseClasses .= ( $window ? ' mwai-window' : '' ); $baseClasses .= ( ! $window && $fullscreen ? ' mwai-fullscreen' : '' ); $baseClasses .= ( $style === 'chatgpt' ? ' mwai-chatgpt' : '' ); $baseClasses .= ( $window && ! empty ( $iconPosition ) ? ( ' mwai-' . $iconPosition ) : '' ); // Output CSS ob_start(); $style_content = '' ; if ( $style === 'chatgpt' ) { $style_content = $this ->chatgpt_style( $id , $style ); } $style_content = apply_filters( 'mwai_chatbot_style' , $style_content , $id ); echo wp_kses( $style_content , array ( 'style' => array () ) ); // Output HTML & CSS $chatStyles = $this ->core->get_option( 'shortcode_chat_styles' ); $iconUrl = MWAI_URL . '/images/chat-green.svg' ; if ( ! empty ( $icon ) ) { $iconUrl = $icon ; } else if ( ! empty ( $chatStyles ) && isset( $chatStyles [ 'icon' ] ) ) { $url = $chatStyles [ 'icon' ]; $iconUrl = $this ->core->isUrl( $url ) ? $url : ( MWAI_URL . 'images/' . $chatStyles [ 'icon' ] ); } ?> <div id= "mwai-chat-<?php echo esc_attr( $id ); ?>" class = "<?php echo esc_attr( $baseClasses ); ?>" > <?php if ( $window ) : ?> <div class = "mwai-open-button" > <?php if ( ! empty ( $iconText ) ) : ?> <div class = "mwai-icon-text" ><?php echo esc_html( $iconText ); ?></div> <?php endif ; ?> <img width= "64" height= "64" alt= "<?php echo esc_attr( $iconAlt ); ?>" src= "<?php echo esc_url( $iconUrl ); ?>" /> </div> <div class = "mwai-header" > <div class = "mwai-buttons" > <?php if ( $fullscreen ) : ?> <div class = "mwai-resize-button" ></div> <?php endif ; ?> <div class = "mwai-close-button" ></div> </div> </div> <?php endif ; ?> <div class = "mwai-content" > <div class = "mwai-conversation" > </div> <div class = "mwai-input" > <textarea rows= "1" maxlength= "<?php echo (int)$textInputMaxLength; ?>" placeholder= "<?php echo esc_attr( $textInputPlaceholder ); ?>" ></textarea> <button><span><?php echo esc_html( $textSend ); ?></span></button> </div> <?php if ( ! empty ( $textCompliance ) ) : ?> <div class = "mwai-compliance" > <img draggable= "false" role= "img" class = "emoji" alt= " src= "https://s.w.org/images/core/emoji/15.1.0/svg/26a0.svg" > <?php echo wp_kses_post( $textCompliance ); ?> </div> <?php endif ; ?> </div> </div> <script> ( function () { let isMobile = window.matchMedia( "only screen and (max-width: 760px)" ).matches; let isWindow = <?php echo $window ? 'true' : 'false' ?>; let isDebugMode = <?php echo $debugMode ? 'true' : 'false' ?>; let isFullscreen = <?php echo $fullscreen ? 'true' : 'false' ?>; let restNonce = '<?php echo esc_attr( $rest_nonce ) ?>' ; let apiURL = '<?php echo esc_url( $apiUrl ) ?>' ; let isCasuallyFineTuned = <?php echo $casuallyFineTuned ? 'true' : 'false' ?>; let rawUserName = '<?php echo esc_attr( $rawUserName ) ?>' ; let rawAiName = '<?php echo esc_attr( $rawAiName ) ?>' ; let userName = '<?php echo wp_kses_post( $userName ) ?>' ; let aiName = '<?php echo wp_kses_post( $aiName ) ?>' ; let sysName = '<?php echo wp_kses_post( $sysName ) ?>' ; let env = '<?php echo esc_attr( $env ) ?>' ; let apiKey = '<?php echo esc_attr( $apiKey ) ?>' ; let service = '<?php echo esc_attr( $service ) ?>' ; let session = '<?php echo esc_attr( $sessionId ) ?>' ; let mode = '<?php echo esc_attr( $mode ) ?>' ; let model = '<?php echo esc_attr( $model ) ?>' ; let context = isCasuallyFineTuned ? null : '<?php echo esc_attr( $context ) ?>' ; let embeddingsIndex = '<?php echo esc_attr( $embeddingsIndex ) ?>' ; let promptEnding = '<?php echo esc_attr( $promptEnding ) ?>' ; let stop = '<?php echo esc_attr( $completionEnding ) ?>' ; let startSentence = '<?php echo esc_attr( $startSentence ) ?>' ; let maxSentences = <?php echo (int) $maxSentences ?>; let memorizeChat = <?php echo $memorizeChat ? 'true' : 'false' ?>; let maxTokens = <?php echo (int) $maxTokens ?>; let maxResults = <?php echo (int) $maxResults ?>; let temperature = <?php echo str_replace ( ',' , '.' , (float) $temperature ) ?>; let typewriter = <?php echo $typewriter ? 'true' : 'false' ?>; let copyButton = <?php echo $copyButton ? 'true' : 'false' ?>; let chatId = randomStr(); let memorizedChat = { chatId, messages: [] }; if (isDebugMode) { window.mwai_<?php echo esc_attr( $id ) ?> = { memorizedChat: memorizedChat, parameters: { mode: mode, model, temperature, maxTokens, context: context, startSentence, isMobile, isWindow, isFullscreen, isCasuallyFineTuned, memorizeChat, maxSentences, rawUserName, rawAiName, embeddingsIndex, typewriter, maxResults, userName, aiName, env, apiKey, service, session } }; } function randomStr() { return Math.random().toString(36).substring(2); } // Set button text function setButtonText() { let input = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-input textarea' ); let button = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-input button' ); let buttonSpan = button.querySelector( 'span' ); if (memorizedChat.messages.length < 2) { buttonSpan.innerHTML = '<?php echo esc_html( $textSend ); ?>' ; } else if (!input.value.length) { button.classList.add( 'mwai-clear' ); buttonSpan.innerHTML = '<?php echo esc_html( $textClear ); ?>' ; } else { button.classList.remove( 'mwai-clear' ); buttonSpan.innerHTML = '<?php echo esc_html( $textSend ); ?>' ; } } // Inject timer function injectTimer(element) { let intervalId; let startTime = new Date (); let timerElement = null; function updateTimer() { let now = new Date (); let timer = Math. floor ((now - startTime) / 1000); if (!timerElement) { if (timer > 0.5) { timerElement = document.createElement( 'div' ); timerElement.classList.add( 'mwai-timer' ); element.appendChild(timerElement); } } if (timerElement) { let minutes = Math. floor (timer / 60); let seconds = timer - (minutes * 60); seconds = seconds < 10 ? '0' + seconds : seconds; let display = minutes + ':' + seconds; timerElement.innerHTML = display; } } intervalId = setInterval(updateTimer, 500); return function stopTimer() { clearInterval(intervalId); if (timerElement) { timerElement.remove(); } }; } // Push the reply in the conversation function addReply(text, role = 'user' , replay = false) { var conversation = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-conversation' ); if (memorizeChat) { localStorage.setItem( 'mwai-chat-<?php echo esc_attr( $id ) ?>' , JSON.stringify(memorizedChat)); } // If text is array, then it's image URLs. Let's create a simple gallery in HTML in $text. if (Array.isArray(text)) { var newText = '<div class="mwai-gallery">' ; for ( var i = 0; i < text.length; i++) { newText += '<a href="' + text[i] + '" target="_blank"><img src="' + text[i] + '" />' ; } text = newText + '</div>' ; } var mwaiClasses = [ 'mwai-reply' ]; if (role === 'assistant' ) { mwaiClasses.push( 'mwai-ai' ); } else if (role === 'system' ) { mwaiClasses.push( 'mwai-system' ); } else { mwaiClasses.push( 'mwai-user' ); } var div = document.createElement( 'div' ); div.classList.add(...mwaiClasses); var nameSpan = document.createElement( 'span' ); nameSpan.classList.add( 'mwai-name' ); if (role === 'assistant' ) { nameSpan.innerHTML = aiName; } else if (role === 'system' ) { nameSpan.innerHTML = sysName; } else { nameSpan.innerHTML = userName; } var textSpan = document.createElement( 'span' ); textSpan.classList.add( 'mwai-text' ); textSpan.innerHTML = text; div.appendChild(nameSpan); div.appendChild(textSpan); // Copy Button if (copyButton && role === 'assistant' ) { var button = document.createElement( 'div' ); button.classList.add( 'mwai-copy-button' ); var firstElement = document.createElement( 'div' ); firstElement.classList.add( 'mwai-copy-button-one' ); var secondElement = document.createElement( 'div' ); secondElement.classList.add( 'mwai-copy-button-two' ); button.appendChild(firstElement); button.appendChild(secondElement); div.appendChild(button); button.addEventListener( 'click' , function () { try { var content = textSpan.textContent; navigator.clipboard.writeText(content); button.classList.add( 'mwai-animate' ); setTimeout( function () { button.classList.remove( 'mwai-animate' ); }, 1000); } catch (err) { console.warn( 'Not allowed to copy to clipboard. Make sure your website uses HTTPS.' ); } }); } conversation.appendChild(div); if (typewriter) { if (role === 'assistant' && text !== startSentence && !replay) { let typewriter = new Typewriter(textSpan, { deleteSpeed: 50, delay: 25, loop: false, cursor: '' , autoStart: true, wrapperClassName: 'mwai-typewriter' , }); typewriter.typeString(text).start().callFunction((state) => { state.elements.cursor.setAttribute( 'hidden' , 'hidden' ); typewriter.stop(); }); } } conversation.scrollTop = conversation.scrollHeight; setButtonText(); // Syntax coloring if (typeof hljs !== 'undefined' ) { document.querySelectorAll( 'pre code' ).forEach((el) => { hljs.highlightElement(el); }); } } function buildPrompt(last = 15) { let prompt = context ? (context + '\n\n' ) : '' ; memorizedChat.messages = memorizedChat.messages.slice(-last); // Casually fine tuned, let's use the last question if (isCasuallyFineTuned) { let lastLine = memorizedChat.messages[memorizedChat.messages.length - 1]; prompt = lastLine.content + promptEnding; return prompt; } // Otherwise let's compile the latest conversation let conversation = memorizedChat.messages.map(x => x.who + x.content); prompt += conversation.join( '\n' ); prompt += '\n' + rawAiName; return prompt; } // Function to request the completion function onSendClick() { let input = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-input textarea' ); let inputText = input.value.trim(); // Reset the conversation if empty if (inputText === '' ) { chatId = randomStr(); document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-conversation' ).innerHTML = '' ; localStorage.removeItem( 'mwai-chat-<?php echo esc_attr( $id ) ?>' ) memorizedChat = { chatId: chatId, messages: [] }; memorizedChat.messages.push({ id: randomStr(), role: 'assistant' , content: startSentence, who: rawAiName, html: startSentence }); addReply(startSentence, 'assistant' ); return ; } // Disable the button var button = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-input button' ); button.disabled = true; // Add the user reply memorizedChat.messages.push({ id: randomStr(), role: 'user' , content: inputText, who: rawUserName, html: inputText }); addReply(inputText, 'user' ); input.value = '' ; input.setAttribute( 'rows' , 1); input.disabled = true; let prompt = buildPrompt(maxSentences); const data = mode === 'images' ? { env, session: session, prompt: inputText, newMessage: inputText, model: model, maxResults, apiKey: apiKey, service: service, chatId: chatId, } : { env, session: session, prompt: prompt, context: context, messages: memorizedChat.messages, newMessage: inputText, userName: userName, aiName: aiName, model: model, temperature: temperature, maxTokens: maxTokens, maxResults: 1, apiKey: apiKey, service: service, embeddingsIndex: embeddingsIndex, stop: stop, chatId: chatId, }; // Start the timer const stopTimer = injectTimer(button); // Send the request if (isDebugMode) { console.log( '[BOT] Sent: ' , data); } fetch(apiURL, { method: 'POST' , headers: { 'Content-Type' : 'application/json' , 'X-WP-Nonce' : restNonce, }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { if (isDebugMode) { console.log( '[BOT] Recv: ' , data); } if (!data.success) { addReply(data.message, 'system' ); } else { let html = data.images ? data.images : data.html; memorizedChat.messages.push({ id: randomStr(), role: 'assistant' , content: data.reply, who: rawAiName, html: html }); addReply(html, 'assistant' ); } button.disabled = false; input.disabled = false; stopTimer(); // Only focus only on desktop (to avoid the mobile keyboard to kick-in) if (!isMobile) { input.focus(); } }) . catch (error => { console.error(error); button.disabled = false; input.disabled = false; stopTimer(); }); } // Keep the textarea height in sync with the content function resizeTextArea(ev) { ev.target.style.height = 'auto' ; ev.target.style.height = ev.target.scrollHeight + 'px' ; } // Keep the textarea height in sync with the content function delayedResizeTextArea(ev) { window.setTimeout(resizeTextArea, 0, event); } // Init the chatbot function initMeowChatbot() { var input = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-input textarea' ); var button = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-input button' ); input.addEventListener( 'keypress' , (event) => { let text = event.target.value; if (event.keyCode === 13 && !text.length && !event.shiftKey) { event.preventDefault(); return ; } if (event.keyCode === 13 && text.length && !event.shiftKey) { onSendClick(); } }); input.addEventListener( 'keydown' , (event) => { var rows = input.getAttribute( 'rows' ); if (event.keyCode === 13 && event.shiftKey) { var lines = input.value.split( '\n' ).length + 1; //mwaiSetTextAreaHeight(input, lines); } }); input.addEventListener( 'keyup' , (event) => { var rows = input.getAttribute( 'rows' ); var lines = input.value.split( '\n' ).length ; //mwaiSetTextAreaHeight(input, lines); setButtonText(); }); input.addEventListener( 'change' , resizeTextArea, false); input.addEventListener( 'cut' , delayedResizeTextArea, false); input.addEventListener( 'paste' , delayedResizeTextArea, false); input.addEventListener( 'drop' , delayedResizeTextArea, false); input.addEventListener( 'keydown' , delayedResizeTextArea, false); button.addEventListener( 'click' , (event) => { onSendClick(); }); // If window, add event listener to mwai-open-button and mwai-close-button if ( isWindow ) { var openButton = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-open-button' ); openButton.addEventListener( 'click' , (event) => { var chat = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?>' ); chat.classList.add( 'mwai-open' ); // Only focus only on desktop (to avoid the mobile keyboard to kick-in) if (!isMobile) { input.focus(); } }); var closeButton = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-close-button' ); closeButton.addEventListener( 'click' , (event) => { var chat = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?>' ); chat.classList.remove( 'mwai-open' ); }); if (isFullscreen) { var resizeButton = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?> .mwai-resize-button' ); resizeButton.addEventListener( 'click' , (event) => { var chat = document.querySelector( '#mwai-chat-<?php echo esc_attr( $id ) ?>' ); chat.classList.toggle( 'mwai-fullscreen' ); }); } } // Get back the previous chat if any for the same ID var chatHistory = []; if (memorizeChat) { chatHistory = localStorage.getItem( 'mwai-chat-<?php echo esc_attr( $id ) ?>' ); if (chatHistory) { memorizedChat = JSON.parse(chatHistory); if (memorizedChat && memorizedChat.chatId && memorizedChat.messages) { chatId = memorizedChat.chatId; memorizedChat.messages = memorizedChat.messages.filter(x => x && x.html && x.role); memorizedChat.messages.forEach(x => { addReply(x.html, x.role, true); }); } else { memorizedChat = null; } } if (!memorizedChat) { memorizedChat = { chatId: chatId, messages: [] }; } } if (memorizedChat.messages.length === 0) { memorizedChat.messages.push({ id: randomStr(), role: 'assistant' , content: startSentence, who: rawAiName, html: startSentence }); addReply(startSentence, 'assistant' ); } } // Let's go totally meoooow on this! initMeowChatbot(); })(); </script> <?php $output = ob_get_contents(); ob_end_clean(); $output = apply_filters( 'mwai_chatbot' , $output , $atts ); return $output ; } |
Code file location:
ai-engine/ai-engine/classes/modules/chatbot_legacy.php
AI Engine [mwai_imagesbot] Shortcode
The ‘mwai_imagesbot’ shortcode is a part of the AI-engine plugin which facilitates image-based chat. This shortcode activates the ‘imageschat’ function, setting the mode to ‘images’. This allows the chat feature to handle and display image content.
Shortcode: [mwai_imagesbot]
Examples and Usage
Basic example – A simple usage of the ‘mwai_imagesbot’ shortcode to invoke the imageschat function without passing any specific parameters.
[mwai_imagesbot /]
Advanced examples
Passing the ‘mode’ parameter explicitly. Even though the ‘mode’ is set to ‘images’ by default in the imageschat function, this example demonstrates how you can pass it explicitly if needed.
[mwai_imagesbot mode="images" /]
Passing multiple parameters to the shortcode. This example demonstrates how you can pass more than one parameter to the shortcode. The ‘mode’ parameter is set to ‘images’, and an additional parameter ‘style’ is set to ‘gallery’. This could be useful if your imageschat function is designed to handle additional parameters to control its behavior.
[mwai_imagesbot mode="images" style="gallery" /]
Note: The actual effect of these parameters will depend on how the imageschat function is implemented. The examples above are for illustrative purposes and may not reflect the actual behavior of your specific implementation.
PHP Function Code
In case you have difficulties debugging what causing issues with [mwai_imagesbot]
shortcode, check below the related PHP functions code.
Shortcode line:
add_shortcode( 'mwai_imagesbot', array( $this, 'imageschat' ) );
Shortcode PHP function:
1 2 3 4 | function imageschat( $atts ) { $atts [ 'mode' ] = 'images' ; return $this ->chat( $atts ); } |
Code file location:
ai-engine/ai-engine/classes/modules/chatbot_legacy.php
Conclusion
Now that you’ve learned how to embed the Ai Engine Plugin shortcodes, understood the parameters, and seen code examples, it’s easy to use and debug any issue that might cause it to ‘not work’. If you still have difficulties with it, don’t hesitate to leave a comment below.
Leave a Reply