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.1.6 1.6.86 0.1.7 1.6.87 0.1.8 1.6.88 0.1.9 1.6.89 0.2.0 1.6.90
ai-engine / classes / modules / discussions.php
ai-engine / classes / modules Last commit date
advisor.php 2 years ago chatbot.php 1 year ago discussions.php 1 year ago files.php 1 year ago gdpr.php 1 year ago security.php 1 year ago tasks.php 2 years ago wand.php 1 year ago
discussions.php
504 lines
1 <?php
2
3 class Meow_MWAI_Modules_Discussions {
4 private $wpdb = null;
5 private $core = null;
6 public $table_chats = null;
7 private $db_check = false;
8 private $namespace_admin = 'mwai/v1';
9 private $namespace_ui = 'mwai-ui/v1';
10
11 public function __construct( ) {
12 global $wpdb;
13 $this->wpdb = $wpdb;
14 global $mwai_core;
15 $this->core = $mwai_core;
16 $this->table_chats = $wpdb->prefix . 'mwai_chats';
17
18 if ( $this->core->get_option( 'chatbot_discussions' ) ) {
19 add_filter( 'mwai_chatbot_reply', [ $this, 'chatbot_reply' ], 10, 4 );
20 add_action( 'rest_api_init', [ $this, 'rest_api_init' ] );
21
22 // TEMPORARY:
23 $timestamp = wp_next_scheduled( 'mwai_discussions' );
24 if ( $timestamp ) {
25 wp_unschedule_event( $timestamp, 'mwai_discussions' );
26 }
27 if ( !wp_next_scheduled( 'mwai_discussions' ) ) {
28 wp_schedule_event( time(), 'hourly', 'mwai_discussions' );
29 }
30 add_action( 'mwai_discussions', [ $this, 'cron_discussions' ] );
31 }
32 }
33
34 public function rest_api_init() {
35
36 // Admin
37 register_rest_route( $this->namespace_admin, '/discussions/list', [
38 'methods' => 'POST',
39 'callback' => [ $this, 'rest_discussions_list' ],
40 'permission_callback' => [ $this->core, 'can_access_settings' ],
41 ] );
42 register_rest_route( $this->namespace_admin, '/discussions/delete', [
43 'methods' => 'POST',
44 'callback' => [ $this, 'rest_discussions_delete' ],
45 'permission_callback' => [ $this->core, 'can_access_settings' ],
46 ] );
47
48 // UI
49 register_rest_route( $this->namespace_ui, '/discussions/list', [
50 'methods' => 'POST',
51 'callback' => [ $this, 'rest_discussions_ui_list' ],
52 'permission_callback' => '__return_true'
53 ] );
54 register_rest_route( $this->namespace_ui, '/discussions/edit', [
55 'methods' => 'POST',
56 'callback' => [ $this, 'rest_discussions_ui_edit' ],
57 'permission_callback' => '__return_true'
58 ] );
59 register_rest_route( $this->namespace_ui, '/discussions/delete', [
60 'methods' => 'POST',
61 'callback' => [ $this, 'rest_discussions_delete' ],
62 'permission_callback' => [ $this, 'can_delete_discussion' ],
63 ] );
64 }
65
66 function can_delete_discussion( $request ) {
67 $params = $request->get_json_params();
68 $chatIds = isset( $params['chatIds'] ) ? $params['chatIds'] : null;
69 $userId = get_current_user_id();
70 if ( !$userId ) {
71 return false;
72 }
73 foreach ( $chatIds as $chatId ) {
74 $chat = $this->wpdb->get_row( $this->wpdb->prepare( "SELECT *
75 FROM $this->table_chats
76 WHERE chatId = %s", $chatId
77 )
78 );
79 if ( !$chat || (int)$chat->userId !== (int)$userId ) {
80 return false;
81 }
82 }
83 return true;
84 }
85
86 function rest_discussions_list( $request ) {
87 try {
88 $params = $request->get_json_params();
89 $offset = $params['offset'];
90 $limit = $params['limit'];
91 $filters = $params['filters'];
92 $sort = $params['sort'];
93 $chats = $this->chats_query( [], $offset, $limit, $filters, $sort );
94 return new WP_REST_Response([ 'success' => true, 'total' => $chats['total'], 'chats' => $chats['rows'] ], 200 );
95 }
96 catch ( Exception $e ) {
97 return new WP_REST_Response([ 'success' => false, 'message' => $e->getMessage() ], 500 );
98 }
99 }
100
101 function rest_discussions_ui_edit( $request ) {
102 try {
103 $params = $request->get_json_params();
104 $chatId = isset( $params['chatId'] ) ? sanitize_text_field( $params['chatId'] ) : null;
105 $title = isset( $params['title'] ) ? sanitize_text_field( $params['title'] ) : null;
106
107 if ( is_null( $chatId ) || is_null( $title ) ) {
108 return new WP_REST_Response( [ 'success' => false, 'message' => 'chatId and title are required.' ], 400 );
109 }
110
111 $userId = get_current_user_id();
112 if ( ! $userId ) {
113 return new WP_REST_Response( [ 'success' => false, 'message' => 'You need to be logged in.' ], 401 );
114 }
115
116 // Update the discussion title for the current user
117 $updated = $this->wpdb->update(
118 $this->table_chats,
119 [ 'title' => $title ],
120 [ 'chatId' => $chatId, 'userId' => $userId ]
121 );
122
123 if ( $updated === false ) {
124 return new WP_REST_Response( [ 'success' => false, 'message' => 'Failed to update the discussion.' ], 500 );
125 }
126
127 return new WP_REST_Response( [ 'success' => true ], 200 );
128 } catch ( Exception $e ) {
129 return new WP_REST_Response( [ 'success' => false, 'message' => $e->getMessage() ], 500 );
130 }
131 }
132
133 function cron_discussions() {
134 $this->check_db();
135 $now = date( 'Y-m-d H:i:s' );
136 $ten_days_ago = date( 'Y-m-d H:i:s', strtotime( '-10 days' ) );
137
138 // Get 5 latest discussions, not older than 10 days, which have no 'title' yet (NULL)
139 $query = $this->wpdb->prepare(
140 "SELECT * FROM {$this->table_chats}
141 WHERE title IS NULL AND updated >= %s
142 ORDER BY updated DESC LIMIT 5",
143 $ten_days_ago
144 );
145 $discussions = $this->wpdb->get_results( $query );
146
147 if ( empty( $discussions ) ) {
148 return;
149 }
150
151 foreach ( $discussions as $discussion ) {
152 $messages = json_decode( $discussion->messages, true );
153 if ( ! is_array( $messages ) ) {
154 continue;
155 }
156
157 $has_user_message = false;
158 $has_assistant_message = false;
159
160 // Check for at least one message from 'user' and one from 'assistant'
161 foreach ( $messages as $message ) {
162 if ( isset( $message['role'] ) ) {
163 if ( $message['role'] === 'user' ) {
164 $has_user_message = true;
165 }
166 if ( $message['role'] === 'assistant' ) {
167 $has_assistant_message = true;
168 }
169 }
170 if ( $has_user_message && $has_assistant_message ) {
171 break;
172 }
173 }
174
175 if ( ! ( $has_user_message && $has_assistant_message ) ) {
176 continue;
177 }
178
179 // Prepare the conversation text for the prompt
180 $conversation_text = '';
181 foreach ( $messages as $message ) {
182 if ( isset( $message['role'] ) && isset( $message['content'] ) ) {
183 $role = ucfirst( $message['role'] );
184 $content = $message['content'];
185 $conversation_text .= "$role: $content\n";
186 }
187 }
188
189 $base_prompt = "Based on the following conversation, generate a concise and specific title for the discussion, strictly less than 64 characters. Focus on the main topic, avoiding unnecessary words such as articles, pronouns, or adjectives. Do not include any punctuation at the end. Do not include anything else than the title itself, only one sentence, no line breaks, just the title.\n\nConversation:\n$conversation_text\n";
190 $prompt = apply_filters( 'mwai_discussions_title_prompt', $base_prompt, $conversation_text, $discussion );
191
192 // Run the AI query
193 global $mwai;
194 $answer = $mwai->simpleTextQuery( $prompt, [ "scope" => 'discussions' ] );
195
196 // Clean up the answer
197 $title = trim( $answer );
198 $title = rtrim( $title, ".!?:;,—–-–" ); // Remove trailing punctuation
199 $title = substr( $title, 0, 64 ); // Ensure less than 64 characters
200 if ( empty( $title ) ) {
201 $title = 'Untitled';
202 }
203
204 // Update the discussion with the title
205 $updated = $this->wpdb->update(
206 $this->table_chats,
207 [ 'title' => $title ],
208 [ 'id' => $discussion->id ]
209 );
210
211 // If the update fails, you can log an error (optional)
212 if ( $updated === false ) {
213 error_log( "Failed to update the title for discussion ID {$discussion->id}" );
214 // Optionally, you could set a default title or take other action
215 }
216 }
217 }
218
219 function rest_discussions_ui_list( $request ) {
220 try {
221 $params = $request->get_json_params();
222 $offset = isset( $params['offset'] ) ? $params['offset'] : 0;
223 $limit = isset( $params['limit'] ) ? $params['limit'] : 10;
224 $botId = isset( $params['botId'] ) ? $params['botId'] : null;
225 $customId = isset( $params['customId'] ) ? $params['customId'] : null;
226
227 if ( !is_null( $customId ) ) {
228 $botId = $customId;
229 }
230
231 if ( is_null( $botId ) ) {
232 return new WP_REST_Response([ 'success' => false, 'message' => "Bot ID is required." ], 200 );
233 }
234
235 $userId = get_current_user_id();
236 if ( !$userId ) {
237 return new WP_REST_Response([ 'success' => false, 'message' => "You need to be connected." ], 200 );
238 }
239 $filters = [
240 [ 'accessor' => 'user', 'value' => $userId ],
241 [ 'accessor' => 'botId', 'value' => $botId ],
242 ];
243 $chats = $this->chats_query( [], $offset, $limit, $filters );
244 return new WP_REST_Response([ 'success' => true, 'total' => $chats['total'], 'chats' => $chats['rows'] ], 200 );
245 }
246 catch ( Exception $e ) {
247 return new WP_REST_Response([ 'success' => false, 'message' => $e->getMessage() ], 500 );
248 }
249 }
250
251 function rest_discussions_delete( $request ) {
252 try {
253 $params = $request->get_json_params();
254 $chatIds = isset( $params['chatIds'] ) ? $params['chatIds'] : null;
255
256 if ( ! is_array( $chatIds ) || empty( $chatIds ) ) {
257 return new WP_REST_Response( [ 'success' => false, 'message' => 'chatIds is required.' ], 400 );
258 }
259
260 $userId = get_current_user_id();
261 if ( ! $userId ) {
262 return new WP_REST_Response( [ 'success' => false, 'message' => 'You need to be logged in.' ], 401 );
263 }
264
265 foreach ( $chatIds as $chatId ) {
266 $this->wpdb->delete( $this->table_chats, [ 'chatId' => $chatId, 'userId' => $userId ] );
267 }
268
269 return new WP_REST_Response( [ 'success' => true ], 200 );
270 } catch ( Exception $e ) {
271 return new WP_REST_Response( [ 'success' => false, 'message' => $e->getMessage() ], 500 );
272 }
273 }
274
275 // Get latest discussion for the given parameter
276 function get_discussion( $botId, $chatId ) {
277 $this->check_db();
278 $chat = $this->wpdb->get_row( $this->wpdb->prepare( "SELECT *
279 FROM $this->table_chats
280 WHERE chatId = %s AND botId = %s", $chatId, $botId
281 ), ARRAY_A );
282 if ( $chat ) {
283 $chat['messages'] = json_decode( $chat['messages'] );
284 return $chat;
285 }
286 return null;
287 }
288
289 function chats_query( $chats = [], $offset = 0, $limit = null, $filters = null, $sort = null ) {
290 $this->check_db();
291 $offset = !empty( $offset ) ? intval( $offset ) : 0;
292 $limit = !empty( $limit ) ? intval( $limit ) : 5;
293 $filters = !empty( $filters ) ? $filters : [];
294 $this->core->sanitize_sort( $sort, 'updated', 'DESC' );
295
296 $where_clauses = [];
297 $where_values = [];
298
299 if ( is_array( $filters ) ) {
300 foreach ( $filters as $filter ) {
301 $value = $filter['value'];
302 if ( is_null( $value ) || $value === '' ) {
303 continue;
304 }
305
306 switch ( $filter['accessor'] ) {
307 case 'user':
308 $isIP = filter_var( $value, FILTER_VALIDATE_IP );
309 if ( $isIP ) {
310 $where_clauses[] = 'ip = %s';
311 $where_values[] = $value;
312 } else {
313 $where_clauses[] = 'userId = %d';
314 $where_values[] = intval( $value );
315 }
316 break;
317
318 case 'botId':
319 $where_clauses[] = 'botId = %s';
320 $where_values[] = $value;
321 break;
322
323 case 'preview':
324 $like = '%' . $this->wpdb->esc_like( $value ) . '%';
325 $where_clauses[] = 'messages LIKE %s';
326 $where_values[] = $like;
327 break;
328
329 // Add other cases as needed
330 }
331 }
332 }
333
334 $where_sql = '';
335 if ( !empty( $where_clauses ) ) {
336 $where_sql = 'WHERE ' . implode( ' AND ', $where_clauses );
337 }
338
339 $order_by = 'ORDER BY ' . esc_sql( $sort['accessor'] ) . ' ' . esc_sql( $sort['by'] );
340
341 $limit_sql = '';
342 if ( $limit > 0 ) {
343 $limit_sql = $this->wpdb->prepare( 'LIMIT %d, %d', $offset, $limit );
344 }
345
346 $query = "SELECT * FROM {$this->table_chats} {$where_sql} {$order_by} {$limit_sql}";
347
348 // Execute the prepared statement
349 $chats['rows'] = $this->wpdb->get_results( $this->wpdb->prepare( $query, $where_values ), ARRAY_A );
350
351 // Get the total count
352 $count_query = "SELECT COUNT(*) FROM {$this->table_chats} {$where_sql}";
353 $chats['total'] = $this->wpdb->get_var( $this->wpdb->prepare( $count_query, $where_values ) );
354
355 return $chats;
356 }
357
358 public function chatbot_reply( $rawText, $query, $params, $extra ) {
359 global $mwai_core;
360 $userIp = $mwai_core->get_ip_address();
361 $userId = $mwai_core->get_user_id();
362 $botId = isset( $params['botId'] ) ? $params['botId'] : null;
363 $chatId = $this->core->fix_chat_id( $query, $params );
364 $customId = isset( $params['customId'] ) ? $params['customId'] : null;
365 $threadId = $query instanceof Meow_MWAI_Query_Assistant ? $query->threadId : null;
366 $storeId = $query instanceof Meow_MWAI_Query_Assistant ? $query->storeId : null;
367 $now = date( 'Y-m-d H:i:s' );
368
369 if ( !empty( $customId ) ) {
370 $botId = $customId;
371 }
372 $newMessage = isset( $params['newMessage'] ) ? $params['newMessage'] : $query->get_message();
373
374 // If there is a file for "Vision", add it to the message
375 if ( isset( $query->filePurpose ) && $query->filePurpose === 'vision' && isset( $query->file ) ) {
376 $newMessage = "![Uploaded Image]({$query->file})\n" . $newMessage;
377 }
378
379 //$chatId = hash( 'sha256', $userIp . $userId . $clientChatId );
380 $this->check_db();
381 $chat = $this->wpdb->get_row( $this->wpdb->prepare( "SELECT *
382 FROM $this->table_chats
383 WHERE chatId = %s", $chatId
384 )
385 );
386 $messageExtra = [
387 'embeddings' => isset( $extra['embeddings'] ) ? $extra['embeddings'] : null
388 ];
389 $chatExtra = [
390 'session' => $query->session,
391 'model' => $query->model,
392 ];
393 if ( !empty( $query->temperature ) ) {
394 $chatExtra['temperature'] = $query->temperature;
395 }
396 if ( !empty( $query->context ) ) {
397 $chatExtra['context'] = $query->context;
398 }
399 if ( $query instanceof Meow_MWAI_Query_Assistant ) {
400 $chatExtra['assistantId'] = $query->assistantId;
401 $chatExtra['threadId'] = $query->threadId;
402 $chatExtra['storeId'] = $query->storeId;
403 }
404 if ( $chat ) {
405 $chat->messages = json_decode( $chat->messages );
406 $chat->messages[] = [ 'role' => 'user', 'content' => $newMessage ];
407 $chat->messages[] = [ 'role' => 'assistant', 'content' => $rawText, 'extra' => $messageExtra ];
408 $chat->messages = json_encode( $chat->messages );
409 $this->wpdb->update( $this->table_chats, [
410 'userId' => $userId,
411 'messages' => $chat->messages,
412 'updated' => $now
413 ], [ 'id' => $chat->id ] );
414 }
415 else {
416 $chat = [
417 'userId' => $userId,
418 'ip' => $userIp,
419 'messages' => json_encode( [
420 [ 'role' => 'user', 'content' => $newMessage ],
421 [ 'role' => 'assistant', 'content' => $rawText, 'extra' => $messageExtra ]
422 ] ),
423 'extra' => json_encode( $chatExtra ),
424 'botId' => $botId,
425 'chatId' => $chatId,
426 'threadId' => $threadId,
427 'storeId' => $storeId,
428 'created' => $now,
429 'updated' => $now
430 ];
431 $this->wpdb->insert( $this->table_chats, $chat );
432 }
433 return $rawText;
434 }
435
436 function format_messages( $json, $format = 'html' ) {
437 $html = '';
438 if ( $format === 'html' ) {
439 try {
440 $conversation = json_decode( $json, true );
441 if ( json_last_error() !== JSON_ERROR_NONE ) {
442 return 'Invalid JSON format';
443 }
444 foreach ( $conversation as $message ) {
445 $role = ucfirst( $message['role'] );
446 $html .= '<p><strong>' . htmlspecialchars( $role ) . ':</strong> ' . htmlspecialchars( $message['content'] ) . '</p>';
447 }
448 }
449 catch ( Exception $e ) {
450 error_log( $e->getMessage() );
451 return 'Error while formatting the message';
452 }
453 }
454 $html = apply_filters( 'mwai_discussion_format_messages', $html, $json, $format );
455 return $html;
456 }
457
458 function check_db() {
459 if ( $this->db_check ) {
460 return true;
461 }
462 $this->db_check = !( strtolower(
463 $this->wpdb->get_var( "SHOW TABLES LIKE '$this->table_chats'" ) ) != strtolower( $this->table_chats )
464 );
465 if ( !$this->db_check ) {
466 $this->create_db();
467 $this->db_check = !( strtolower(
468 $this->wpdb->get_var( "SHOW TABLES LIKE '$this->table_chats'" ) ) != strtolower( $this->table_chats )
469 );
470 }
471
472 // LATER: REMOVE THIS AFTER MARCH 2025
473 $this->db_check = $this->db_check && $this->wpdb->get_var( "SHOW COLUMNS FROM $this->table_chats LIKE 'title'" );
474 if ( !$this->db_check ) {
475 $this->wpdb->query( "ALTER TABLE $this->table_chats ADD COLUMN title VARCHAR(64) NULL" );
476 $this->db_check = true;
477 }
478
479 return $this->db_check;
480 }
481
482 function create_db() {
483 $charset_collate = $this->wpdb->get_charset_collate();
484 $sqlLogs = "CREATE TABLE $this->table_chats (
485 id BIGINT(20) NOT NULL AUTO_INCREMENT,
486 userId BIGINT(20) NULL,
487 ip VARCHAR(64) NULL,
488 title VARCHAR(64) NULL,
489 messages TEXT NOT NULL NULL,
490 extra LONGTEXT NOT NULL NULL,
491 botId VARCHAR(64) NULL,
492 chatId VARCHAR(64) NOT NULL,
493 threadId VARCHAR(64) NULL,
494 storeId VARCHAR(64) NULL,
495 created DATETIME NOT NULL,
496 updated DATETIME NOT NULL,
497 PRIMARY KEY (id),
498 INDEX chatId (chatId)
499 ) $charset_collate;";
500 require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
501 dbDelta( $sqlLogs );
502 }
503
504 }