AI Chatbot Assistant on WordPress Backend Code
🔑 ID:
67458
👨💻
PHP
🕒
25/11/2024
Free
Description:
This Code is used to build the backend of the Chatbot to connect with RelevanceAI, as shown in the following tutorial: https://youtu.be/jKXbm1zN4wk
Code:
// Prevent direct access if (!defined('ABSPATH')) { exit; } class RelevanceAI_Chat_Integration { private $project_id; private $auth_token; private $agent_id; private $base_url; public function __construct() { // Initialize with your RelevanceAI credentials $this->project_id = '6b8c8ef52cf7-40db-93cf-3d437f38ab7e'; $this->auth_token = 'sk-MTM4ZTM2NGEtNDBhMi00YzViLWJkMTMtYmFjM2MxOGEzMTRk'; $this->agent_id = 'db4b5fa6-23b1-4a8c-9f89-f5d7a6fb27df'; $this->region_id = 'bcbe5a'; $this->base_url = 'https://api-' . $this->region_id . '.stack.tryrelevance.com/latest/'; // Register REST API endpoint add_action('rest_api_init', array($this, 'register_endpoints')); } public function register_endpoints() { register_rest_route('chatbot/v1', '/chat', array( 'methods' => 'POST', 'callback' => array($this, 'handle_chat_request'), 'permission_callback' => array($this, 'check_permissions'), )); } public function check_permissions() { // Add your permission logic here // For example, require user to be logged in: // return is_user_logged_in(); // Or allow all requests: return true; } public function handle_chat_request($request) { try { $parameters = $request->get_json_params(); if (empty($parameters['message'])) { return new WP_Error('missing_message', 'Message is required', array('status' => 400)); } // Get conversation history if provided $conversation_id = isset($parameters['conversation_id']) ? $parameters['conversation_id'] : null; // Trigger conversation $response = $this->trigger_conversation($parameters['message'], $conversation_id); if (isset($response['job_info'])) { $studio_id = $response['job_info']['studio_id']; $job_id = $response['job_info']['job_id']; // Poll for response $status = $this->poll_for_response($studio_id, $job_id); // Get agent response $agent_response = $this->get_agent_response($status); return new WP_REST_Response(array( 'success' => true, 'response' => $agent_response, 'conversation_id' => $response['conversation_id'] ?? null ), 200); } return new WP_Error('api_error', 'Failed to get response from RelevanceAI', array('status' => 500)); } catch (Exception $e) { return new WP_Error('error', $e->getMessage(), array('status' => 500)); } } private function trigger_conversation($message, $conversation_id = null) { $payload = array( 'message' => array( 'role' => 'user', 'content' => $message ), 'agent_id' => $this->agent_id ); if ($conversation_id) { $payload['conversation_id'] = $conversation_id; } $response = wp_remote_post($this->base_url . 'agents/trigger', array( 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => $this->project_id . ':' . $this->auth_token ), 'body' => json_encode($payload), 'timeout' => 15 )); if (is_wp_error($response)) { throw new Exception($response->get_error_message()); } return json_decode(wp_remote_retrieve_body($response), true); } private function poll_for_response($studio_id, $job_id) { $done = false; $retries = 0; $max_retries = 20; while (!$done && $retries < $max_retries) { $response = wp_remote_get($this->base_url . "studios/{$studio_id}/async_poll/{$job_id}", array( 'headers' => array( 'Authorization' => $this->project_id . ':' . $this->auth_token ), 'timeout' => 15 )); if (is_wp_error($response)) { throw new Exception($response->get_error_message()); } $status = json_decode(wp_remote_retrieve_body($response), true); if (isset($status['updates'])) { foreach ($status['updates'] as $update) { if ($update['type'] === 'chain-success') { return $status; } } } if (!$done) { sleep(3); $retries++; } } throw new Exception('Polling timeout exceeded'); } private function get_agent_response($status) { if (isset($status['updates'])) { foreach ($status['updates'] as $update) { if ($update['type'] === 'chain-success') { if (isset($update['output']['output']['answer'])) { return $update['output']['output']['answer']; } if (isset($update['output']['output']['history_items'])) { $history_items = $update['output']['output']['history_items']; foreach (array_reverse($history_items) as $item) { if (isset($item['role']) && $item['role'] === 'ai') { return $item['message']; } } } } } } return 'No response found from agent'; } } // Initialize the plugin function init_relevance_ai_chat() { new RelevanceAI_Chat_Integration(); } add_action('init', 'init_relevance_ai_chat'); // Add settings page function relevance_ai_chat_menu() { add_options_page( 'RelevanceAI Chat Settings', 'RelevanceAI Chat', 'manage_options', 'relevance-ai-chat', 'relevance_ai_chat_settings_page' ); } add_action('admin_menu', 'relevance_ai_chat_menu'); function relevance_ai_chat_settings_page() { // Add your settings page HTML and form here ?> <div class="wrap"> <h2>RelevanceAI Chat Settings</h2> <form method="post" action="options.php"> <?php settings_fields('relevance_ai_chat_options'); do_settings_sections('relevance-ai-chat'); submit_button(); ?> </form> </div> <?php }
GitHub Link
✖️ Not Available
Download File
✖️ Not Available
If you’re encountering any problems or need further assistance with this code, we’re here to help! Join our community on the forum or Discord for support, tips, and discussion.