1<?php 2/** 3 * DokuWiki Plugin dokullm (Action Component) 4 * 5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html 6 * @author Costin Stroie <costinstroie@eridu.eu.org> 7 */ 8 9// must be run within Dokuwiki 10if (!defined('DOKU_INC')) { 11 die(); 12} 13 14/** 15 * Main action component for the dokullm plugin 16 * 17 * This class handles: 18 * - Registering event handlers for page rendering and AJAX calls 19 * - Adding JavaScript to edit pages 20 * - Processing AJAX requests from the frontend 21 * - Handling page template loading with metadata support 22 * - Adding copy page button to page tools 23 * 24 * The plugin provides integration with LLM APIs for text processing 25 * operations directly within the DokuWiki editor. 26 * 27 * Configuration options: 28 * - api_url: The LLM API endpoint URL 29 * - api_key: Authentication key for the API (optional) 30 * - model: The model identifier to use for requests 31 * - timeout: Request timeout in seconds 32 * - profile: Profile for prompt templates 33 * - temperature: Temperature setting for response randomness (0.0-1.0) 34 * - top_p: Top-p (nucleus sampling) setting (0.0-1.0) 35 * - top_k: Top-k setting (integer >= 1) 36 * - min_p: Minimum probability threshold (0.0-1.0) 37 * - think: Whether to enable thinking in LLM responses (boolean) 38 * - show_copy_button: Whether to show the copy page button (boolean) 39 * - replace_id: Whether to replace template ID when copying (boolean) 40 */ 41class action_plugin_dokullm extends DokuWiki_Action_Plugin 42{ 43 /** 44 * Register the event handlers for this plugin 45 * 46 * Hooks into: 47 * - TPL_METAHEADER_OUTPUT: To add JavaScript to edit pages 48 * - AJAX_CALL_UNKNOWN: To handle plugin-specific AJAX requests 49 * 50 * @param Doku_Event_Handler $controller The event handler controller 51 */ 52 public function register(Doku_Event_Handler $controller) 53 { 54 $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handleMetaHeaders'); 55 $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handleAjax'); 56 $controller->register_hook('COMMON_PAGETPL_LOAD', 'BEFORE', $this, 'handleTemplate'); 57 $controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'addCopyPageButton', array()); 58 $controller->register_hook('INDEXER_TASKS_RUN', 'AFTER', $this, 'handlePageSave'); 59 } 60 61 /** 62 * Add JavaScript to the page header for edit pages 63 * 64 * This method checks if we're on an edit or preview page and adds 65 * the plugin's JavaScript file to the page header. 66 * 67 * @param Doku_Event $event The event object 68 * @param mixed $param Additional parameters 69 */ 70 public function handleMetaHeaders(Doku_Event $event, $param) 71 { 72 global $INFO; 73 74 // Only add JS to edit pages 75 if ($INFO['act'] == 'edit' || $INFO['act'] == 'preview') { 76 $event->data['script'][] = array( 77 'type' => 'text/javascript', 78 'src' => DOKU_BASE . 'lib/plugins/dokullm/script.js', 79 '_data' => 'dokullm' 80 ); 81 } 82 } 83 84 /** 85 * Handle AJAX requests for the plugin 86 * 87 * Processes AJAX calls with the identifier 'plugin_dokullm' and 88 * routes them to the appropriate text processing method. 89 * 90 * @param Doku_Event $event The event object 91 * @param mixed $param Additional parameters 92 */ 93 public function handleAjax(Doku_Event $event, $param) 94 { 95 if ($event->data !== 'plugin_dokullm') { 96 return; 97 } 98 99 $event->stopPropagation(); 100 $event->preventDefault(); 101 102 // Handle the AJAX request 103 $this->processRequest(); 104 } 105 106 /** 107 * Process the AJAX request and return JSON response 108 * 109 * Extracts action, text, prompt, metadata, and template parameters from the request, 110 * validates the input, and calls the appropriate processing method. 111 * Returns JSON encoded result or error. 112 * 113 * @return void 114 */ 115 private function processRequest() 116 { 117 global $INPUT; 118 119 // Get form data 120 $action = $INPUT->str('action'); 121 $text = $INPUT->str('text'); 122 $prompt = $INPUT->str('prompt', ''); 123 $template = $INPUT->str('template', ''); 124 $examples = $INPUT->str('examples', ''); 125 $previous = $INPUT->str('previous', ''); 126 127 // Parse examples - split by newline and filter out empty lines 128 $examplesList = array_filter(array_map('trim', explode("\n", $examples))); 129 130 // Create metadata object with prompt, template, examples, and previous 131 $metadata = [ 132 'prompt' => $prompt, 133 'template' => $template, 134 'examples' => $examplesList, 135 'previous' => $previous 136 ]; 137 138 // Handle the special case of get_actions action 139 if ($action === 'get_actions') { 140 try { 141 $actions = $this->getActions(); 142 echo json_encode(['result' => $actions]); 143 } catch (Exception $e) { 144 http_status(500); 145 echo json_encode(['error' => $e->getMessage()]); 146 } 147 return; 148 } 149 150 // Handle the special case of get_template action 151 if ($action === 'get_template') { 152 try { 153 $templateId = $template; 154 $templateContent = $this->getPageContent($templateId); 155 if ($templateContent === false) { 156 throw new Exception('Template not found: ' . $templateId); 157 } 158 echo json_encode(['result' => ['content' => $templateContent]]); 159 } catch (Exception $e) { 160 http_status(500); 161 echo json_encode(['error' => $e->getMessage()]); 162 } 163 return; 164 } 165 166 // Handle the special case of find_template action 167 if ($action === 'find_template') { 168 try { 169 $searchText = $INPUT->str('text'); 170 $template = $this->findTemplate($searchText); 171 if (!empty($template)) { 172 echo json_encode(['result' => ['template' => $template[0]]]); 173 } else { 174 echo json_encode(['result' => ['template' => null]]); 175 } 176 } catch (Exception $e) { 177 http_status(500); 178 echo json_encode(['error' => $e->getMessage()]); 179 } 180 return; 181 } 182 183 // Validate input 184 if (empty($text)) { 185 http_status(400); 186 echo json_encode(['error' => 'No text provided']); 187 return; 188 } 189 190 191 // Create ChromaDB client only if enabled 192 $chromaClient = null; 193 if ($this->getConf('enable_chromadb')) { 194 $chromaClient = new \dokuwiki\plugin\dokullm\ChromaDBClient( 195 $this->getConf('chroma_host'), 196 $this->getConf('chroma_port'), 197 $this->getConf('chroma_tenant'), 198 $this->getConf('chroma_database'), 199 $this->getConf('chroma_collection'), 200 $this->getConf('ollama_host'), 201 $this->getConf('ollama_port'), 202 $this->getConf('ollama_embeddings_model') 203 ); 204 } 205 206 $client = new \dokuwiki\plugin\dokullm\LlmClient( 207 $this->getConf('api_url'), 208 $this->getConf('api_key'), 209 $this->getConf('model'), 210 $this->getConf('timeout'), 211 $this->getConf('temperature'), 212 $this->getConf('top_p'), 213 $this->getConf('top_k'), 214 $this->getConf('min_p'), 215 $this->getConf('think', false), 216 $this->getConf('profile', 'default'), 217 $chromaClient, 218 $ID, 219 $this->getConf('enable_chromadb') 220 ); 221 try { 222 switch ($action) { 223 case 'custom': 224 $result = $client->processCustomPrompt($text, $metadata); 225 default: 226 $result = $client->process($action, $text, $metadata); 227 } 228 echo json_encode(['result' => $result]); 229 } catch (Exception $e) { 230 http_status(500); 231 echo json_encode(['error' => $e->getMessage()]); 232 } 233 } 234 235 /** 236 * Get action definitions from the DokuWiki table at dokullm:profiles:PROFILE 237 * 238 * Parses the table containing action definitions with the following columns: 239 * 240 * - ID: The action identifier, which corresponds to the prompt name 241 * - Label: The text displayed on the button 242 * - Description: A detailed description of the action, used as a tooltip 243 * - Icon: The icon displayed on the button (can be empty) 244 * - Result: The action to perform with the LLM result: 245 * - show: Display the result in a modal dialog 246 * - append: Add the result to the end of the current content 247 * - replace: Replace the selected content with the result 248 * - insert: Insert the result at the cursor position 249 * 250 * The parsing stops after the first table ends to avoid processing 251 * additional tables that might contain disabled or work-in-progress commands. 252 * 253 * @return array Array of action definitions, each containing: 254 * - id: string, the action identifier 255 * - label: string, the button label 256 * - description: string, the action description 257 * - icon: string, the icon name 258 * - result: string, the result handling method 259 */ 260 private function getActions() 261 { 262 // Get the content of the profile page 263 $profile = $this->getConf('profile', 'default'); 264 $content = $this->getPageContent('dokullm:profiles:' . $profile); 265 266 if ($content === false) { 267 // Return empty list if page doesn't exist 268 return []; 269 } 270 271 // Parse the table from the page content 272 $actions = []; 273 $lines = explode("\n", $content); 274 $inTable = false; 275 276 foreach ($lines as $line) { 277 // Check if this is a table row 278 if (preg_match('/^\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|$/', $line, $matches)) { 279 $inTable = true; 280 281 // Skip header row 282 if (trim($matches[1]) === 'ID' || trim($matches[1]) === 'id') { 283 continue; 284 } 285 286 $actions[] = [ 287 'id' => trim($matches[1]), 288 'label' => trim($matches[2]), 289 'description' => trim($matches[3]), 290 'icon' => trim($matches[4]), 291 'result' => trim($matches[5]) 292 ]; 293 } else if ($inTable) { 294 // We've exited the table, so stop parsing 295 break; 296 } 297 } 298 299 return $actions; 300 } 301 302 /** 303 * Get the content of a DokuWiki page 304 * 305 * Retrieves the raw content of a DokuWiki page by its ID. 306 * Used for loading template and example page content for context. 307 * 308 * @param string $pageId The page ID to retrieve 309 * @return string|false The page content or false if not found/readable 310 */ 311 private function getPageContent($pageId) 312 { 313 // Convert page ID to file path 314 $pageFile = wikiFN($pageId); 315 316 // Check if file exists and is readable 317 if (file_exists($pageFile) && is_readable($pageFile)) { 318 return file_get_contents($pageFile); 319 } 320 321 return false; 322 } 323 324 325 /** 326 * Find an appropriate template based on the provided text 327 * 328 * Uses ChromaDB to search for the most relevant template based on the content. 329 * 330 * @param string $text The text to use for finding a template 331 * @return array The template ID array or empty array if none found 332 * @throws Exception If an error occurs during the search 333 */ 334 private function findTemplate($text) { 335 try { 336 // Create ChromaDB client only if enabled 337 $chromaClient = null; 338 if ($this->getConf('enable_chromadb')) { 339 $chromaClient = new \dokuwiki\plugin\dokullm\ChromaDBClient( 340 $this->getConf('chroma_host'), 341 $this->getConf('chroma_port'), 342 $this->getConf('chroma_tenant'), 343 $this->getConf('chroma_database'), 344 $this->getConf('chroma_collection'), 345 $this->getConf('ollama_host'), 346 $this->getConf('ollama_port'), 347 $this->getConf('ollama_embeddings_model') 348 ); 349 } 350 351 $client = new \dokuwiki\plugin\dokullm\LlmClient( 352 $this->getConf('api_url'), 353 $this->getConf('api_key'), 354 $this->getConf('model'), 355 $this->getConf('timeout'), 356 $this->getConf('temperature'), 357 $this->getConf('top_p'), 358 $this->getConf('top_k'), 359 $this->getConf('min_p'), 360 $this->getConf('think', false), 361 $this->getConf('profile', 'default'), 362 $chromaClient, 363 $ID, 364 $this->getConf('enable_chromadb') 365 ); 366 367 // Query ChromaDB for the most relevant template 368 $template = $client->queryChromaDBTemplate($text); 369 370 return $template; 371 } catch (Exception $e) { 372 throw new Exception('Error finding template: ' . $e->getMessage()); 373 } 374 } 375 376 377 /** 378 * Handle page save event and send page to ChromaDB 379 * 380 * This method is triggered after a page is saved and sends the page content 381 * to ChromaDB for indexing. 382 * 383 * @param Doku_Event $event The event object 384 * @param mixed $param Additional parameters 385 */ 386 public function handlePageSave(Doku_Event $event, $param) 387 { 388 global $ID; 389 390 // Only process if we have a valid page ID 391 if (empty($ID)) { 392 return; 393 } 394 395 // Get the page content 396 $content = rawWiki($ID); 397 398 // Skip empty pages 399 if (empty($content)) { 400 return; 401 } 402 403 try { 404 // Send page to ChromaDB 405 $this->sendPageToChromaDB($ID, $content); 406 } catch (Exception $e) { 407 // Log error but don't stop execution 408 \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $e->getMessage()); 409 } 410 } 411 412 413 /** 414 * Send page content to ChromaDB 415 * 416 * @param string $pageId The page ID 417 * @param string $content The page content 418 * @return void 419 */ 420 private function sendPageToChromaDB($pageId, $content) 421 { 422 // Skip if ChromaDB is disabled 423 if (!$this->getConf('enable_chromadb')) { 424 return; 425 } 426 427 // Convert page ID to file path format for ChromaDB 428 $filePath = wikiFN($pageId); 429 430 try { 431 // Get configuration values 432 $chromaHost = $this->getConf('chroma_host'); 433 $chromaPort = $this->getConf('chroma_port'); 434 $chromaTenant = $this->getConf('chroma_tenant'); 435 $chromaDatabase = $this->getConf('chroma_database'); 436 $ollamaHost = $this->getConf('ollama_host'); 437 $ollamaPort = $this->getConf('ollama_port'); 438 $ollamaModel = $this->getConf('ollama_embeddings_model'); 439 440 // Use the existing ChromaDB client to process the file 441 $chroma = new \dokuwiki\plugin\dokullm\ChromaDBClient( 442 $chromaHost, 443 $chromaPort, 444 $chromaTenant, 445 $chromaDatabase, 446 $this->getConf('chroma_collection'), 447 $ollamaHost, 448 $ollamaPort, 449 $ollamaModel 450 ); 451 452 // Use the first part of the document ID as collection name, fallback to 'documents' 453 $idParts = explode(':', $pageId); 454 $collectionName = isset($idParts[0]) && !empty($idParts[0]) ? $idParts[0] : 'documents'; 455 456 // Process the file directly 457 $result = $chroma->processSingleFile($filePath, $collectionName, false); 458 459 // Log success or failure 460 if ($result['status'] === 'success') { 461 \dokuwiki\Logger::debug('dokullm: Successfully sent page to ChromaDB: ' . $pageId); 462 } else if ($result['status'] === 'skipped') { 463 \dokuwiki\Logger::debug('dokullm: Skipped sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']); 464 } else { 465 \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']); 466 } 467 } catch (Exception $e) { 468 throw $e; 469 } 470 } 471 472 473 /** 474 * Handler to load page template. 475 * 476 * @param Doku_Event $event event object by reference 477 * @param mixed $param [the parameters passed as fifth argument to register_hook() when this 478 * handler was registered] 479 * @return void 480 */ 481 public function handleTemplate(Doku_Event &$event, $param) { 482 if (strlen($_REQUEST['copyfrom']) > 0) { 483 $template_id = $_REQUEST['copyfrom']; 484 if (auth_quickaclcheck($template_id) >= AUTH_READ) { 485 $tpl = io_readFile(wikiFN($template_id)); 486 if ($this->getConf('replace_id')) { 487 $id = $event->data['id']; 488 $tpl = str_replace($template_id, $id, $tpl); 489 } 490 // Add LLM_TEMPLATE metadata if the original page ID contains 'template' 491 if (strpos($template_id, 'template') !== false) { 492 $tpl = '~~LLM_TEMPLATE:' . $template_id . '~~' . "\n" . $tpl; 493 } 494 $event->data['tpl'] = $tpl; 495 $event->preventDefault(); 496 } 497 } 498 } 499 500 501 502 /** 503 * Add 'Copy page' button to page tools, SVG based 504 * 505 * @param Doku_Event $event 506 */ 507 public function addCopyPageButton(Doku_Event $event) 508 { 509 global $INFO; 510 if ($event->data['view'] != 'page' || !$this->getConf('show_copy_button')) { 511 return; 512 } 513 if (! $INFO['exists']) { 514 return; 515 } 516 array_splice($event->data['items'], -1, 0, [new \dokuwiki\plugin\dokullm\MenuItem()]); 517 } 518} 519