xref: /plugin/dokullm/action.php (revision 2f9b87f96cb72c999dae194b32a76566b81c3daa)
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('DOKUWIKI_STARTED', 'AFTER', $this, 'handleDokuwikiStarted');
55        $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handleMetaHeaders');
56        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handleAjax');
57        $controller->register_hook('COMMON_PAGETPL_LOAD', 'BEFORE', $this, 'handleTemplate');
58        $controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'addCopyPageButton', array());
59        $controller->register_hook('INDEXER_TASKS_RUN', 'AFTER', $this, 'handlePageSave');
60    }
61
62    /**
63     * Insert metadata line after the first title in DokuWiki format
64     *
65     * If the first line starts with '=', insert the metadata after it.
66     * Otherwise, insert at the very beginning.
67     *
68     * @param string $text The text content
69     * @param string $metadataLine The metadata line to insert
70     * @return string The text with metadata inserted
71     */
72    private function insertMetadataAfterTitle($text, $metadataLine) {
73        // Check if the first line is a title (starts with = in DokuWiki)
74        $lines = explode("\n", $text);
75        if (count($lines) > 0 && trim($lines[0]) !== '' && trim($lines[0])[0] === '=') {
76            // Insert after the first line (the title)
77            array_splice($lines, 1, 0, $metadataLine);
78            return implode("\n", $lines);
79        } else {
80            // Insert at the very beginning
81            return $metadataLine . "\n" . $text;
82        }
83    }
84
85    /**
86     * Add JavaScript to the page header for edit pages
87     *
88     * This method checks if we're on an edit or preview page and adds
89     * the plugin's JavaScript file to the page header.
90     *
91     * @param Doku_Event $event The event object
92     * @param mixed $param Additional parameters
93     */
94    public function handleMetaHeaders(Doku_Event $event, $param)
95    {
96        global $INFO;
97
98        // Only add JS to edit pages
99        if ($INFO['act'] == 'edit' || $INFO['act'] == 'preview') {
100            $event->data['script'][] = array(
101                'type' => 'text/javascript',
102                'src' => DOKU_BASE . 'lib/plugins/dokullm/script.js',
103                '_data' => 'dokullm'
104            );
105        }
106    }
107
108    /**
109     * Add dokullm configuration to JSINFO
110     *
111     * @param Doku_Event $event The event object
112     * @param mixed $param Additional parameters
113     */
114    public function handleDokuwikiStarted(Doku_Event $event, $param)
115    {
116        global $JSINFO;
117
118        if (!isset($JSINFO['plugins'])) {
119            $JSINFO['plugins'] = [];
120        }
121
122        $JSINFO['plugins']['dokullm'] = [
123            'enable_chromadb' => $this->getConf('enable_chromadb')
124        ];
125    }
126
127    /**
128     * Handle AJAX requests for the plugin
129     *
130     * Processes AJAX calls with the identifier 'plugin_dokullm' and
131     * routes them to the appropriate text processing method.
132     *
133     * @param Doku_Event $event The event object
134     * @param mixed $param Additional parameters
135     */
136    public function handleAjax(Doku_Event $event, $param)
137    {
138        if ($event->data !== 'plugin_dokullm') {
139            return;
140        }
141
142        $event->stopPropagation();
143        $event->preventDefault();
144
145        // Handle the AJAX request
146        $this->processRequest();
147    }
148
149    /**
150     * Process the AJAX request and return JSON response
151     *
152     * Extracts action, text, prompt, metadata, and template parameters from the request,
153     * validates the input, and calls the appropriate processing method.
154     * Returns JSON encoded result or error.
155     *
156     * @return void
157     */
158    private function processRequest()
159    {
160        global $INPUT;
161
162        // Get form data
163        $action = $INPUT->str('action');
164        $text = $INPUT->str('text');
165        $prompt = $INPUT->str('prompt', '');
166        $template = $INPUT->str('template', '');
167        $examples = $INPUT->str('examples', '');
168        $previous = $INPUT->str('previous', '');
169
170        // Parse examples - split by newline and filter out empty lines
171        $examplesList = array_filter(array_map('trim', explode("\n", $examples)));
172
173        // Create metadata object with prompt, template, examples, and previous
174        $metadata = [
175            'prompt' => $prompt,
176            'template' => $template,
177            'examples' => $examplesList,
178            'previous' => $previous
179        ];
180
181        // Handle the special case of get_actions action
182        if ($action === 'get_actions') {
183            try {
184                $actions = $this->getActions();
185                echo json_encode(['result' => $actions]);
186            } catch (Exception $e) {
187                http_status(500);
188                echo json_encode(['error' => $e->getMessage()]);
189            }
190            return;
191        }
192
193        // Handle the special case of get_template action
194        if ($action === 'get_template') {
195            try {
196                $templateId = $template;
197                $templateContent = $this->getPageContent($templateId);
198                if ($templateContent === false) {
199                    throw new Exception('Template not found: ' . $templateId);
200                }
201                echo json_encode(['result' => ['content' => $templateContent]]);
202            } catch (Exception $e) {
203                http_status(500);
204                echo json_encode(['error' => $e->getMessage()]);
205            }
206            return;
207        }
208
209        // Handle the special case of find_template action
210        if ($action === 'find_template') {
211            try {
212                $searchText = $INPUT->str('text');
213                $template = $this->findTemplate($searchText);
214                if (!empty($template)) {
215                    echo json_encode(['result' => ['template' => $template[0]]]);
216                } else {
217                    echo json_encode(['result' => ['template' => null]]);
218                }
219            } catch (Exception $e) {
220                http_status(500);
221                echo json_encode(['error' => $e->getMessage()]);
222            }
223            return;
224        }
225
226        // Validate input
227        if (empty($text)) {
228            http_status(400);
229            echo json_encode(['error' => 'No text provided']);
230            return;
231        }
232
233
234        // Create ChromaDB client only if enabled
235        $chromaClient = null;
236        if ($this->getConf('enable_chromadb')) {
237            $chromaClient = new \dokuwiki\plugin\dokullm\ChromaDBClient(
238                $this->getConf('chroma_host'),
239                $this->getConf('chroma_port'),
240                $this->getConf('chroma_tenant'),
241                $this->getConf('chroma_database'),
242                $this->getConf('chroma_collection'),
243                $this->getConf('ollama_host'),
244                $this->getConf('ollama_port'),
245                $this->getConf('ollama_embeddings_model')
246            );
247        } else {
248            $chromaClient = null;
249        }
250
251        $client = new \dokuwiki\plugin\dokullm\LlmClient(
252            $this->getConf('api_url'),
253            $this->getConf('api_key'),
254            $this->getConf('model'),
255            $this->getConf('timeout'),
256            $this->getConf('temperature'),
257            $this->getConf('top_p'),
258            $this->getConf('top_k'),
259            $this->getConf('min_p'),
260            $this->getConf('think', false),
261            $this->getConf('profile', 'default'),
262            $chromaClient,
263            $ID
264        );
265        try {
266            switch ($action) {
267                case 'custom':
268                    $result = $client->processCustomPrompt($text, $metadata);
269                    break;
270                default:
271                    $result = $client->process($action, $text, $metadata);
272            }
273            echo json_encode(['result' => $result]);
274        } catch (Exception $e) {
275            http_status(500);
276            echo json_encode(['error' => $e->getMessage()]);
277        }
278    }
279
280    /**
281     * Get action definitions from the DokuWiki table at dokullm:profiles:PROFILE
282     *
283     * Parses the table containing action definitions with the following columns:
284     *
285     * - ID: The action identifier, which corresponds to the prompt name
286     * - Label: The text displayed on the button
287     * - Description: A detailed description of the action, used as a tooltip
288     * - Icon: The icon displayed on the button (can be empty)
289     * - Result: The action to perform with the LLM result:
290     *   - show: Display the result in a modal dialog
291     *   - append: Add the result to the end of the current content
292     *   - replace: Replace the selected content with the result
293     *   - insert: Insert the result at the cursor position
294     *
295     * The parsing stops after the first table ends to avoid processing
296     * additional tables that might contain disabled or work-in-progress commands.
297     *
298     * The ID can be either:
299     * - A simple word (e.g., "summary")
300     * - A link to a page in the profile namespace (e.g., "[[.:default:summarize]]")
301     *
302     * For page links, the actual ID is extracted as the last part after the final ':'
303     *
304     * @return array Array of action definitions, each containing:
305     *               - id: string, the action identifier
306     *               - label: string, the button label
307     *               - description: string, the action description
308     *               - icon: string, the icon name
309     *               - result: string, the result handling method
310     */
311    private function getActions()
312    {
313        // Get the content of the profile page
314        $profile = $this->getConf('profile', 'default');
315        $content = $this->getPageContent('dokullm:profiles:' . $profile);
316
317        if ($content === false) {
318            // Return empty list if page doesn't exist
319            return [];
320        }
321
322        // Parse the table from the page content
323        $actions = [];
324        $lines = explode("\n", $content);
325        $inTable = false;
326
327        foreach ($lines as $line) {
328            // Check if this is a table row
329            if (preg_match('/^\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|$/', $line, $matches)) {
330                $inTable = true;
331
332                // Skip header row
333                if (trim($matches[1]) === 'ID' || trim($matches[1]) === 'id') {
334                    continue;
335                }
336
337                // Extract ID from either simple text or page link
338                $rawId = trim($matches[1]);
339                $id = $rawId;
340
341                // Check if ID is a page link in format [[namespace:page]] or [[.:namespace:page]]
342                if (preg_match('/\[\[\.?:?([^\]]+)\]\]/', $rawId, $linkMatches)) {
343                    // Extract the actual page path
344                    $pagePath = $linkMatches[1];
345                    // Get the last part after the final ':' as the ID
346                    $pathParts = explode(':', $pagePath);
347                    $id = end($pathParts);
348                }
349
350                $actions[] = [
351                    'id' => $id,
352                    'label' => trim($matches[2]),
353                    'description' => trim($matches[3]),
354                    'icon' => trim($matches[4]),
355                    'result' => trim($matches[5])
356                ];
357            } else if ($inTable) {
358                // We've exited the table, so stop parsing
359                break;
360            }
361        }
362
363        return $actions;
364    }
365
366    /**
367     * Get the content of a DokuWiki page
368     *
369     * Retrieves the raw content of a DokuWiki page by its ID.
370     * Used for loading template and example page content for context.
371     *
372     * @param string $pageId The page ID to retrieve
373     * @return string|false The page content or false if not found/readable
374     */
375    private function getPageContent($pageId)
376    {
377        // Convert page ID to file path
378        $pageFile = wikiFN($pageId);
379
380        // Check if file exists and is readable
381        if (file_exists($pageFile) && is_readable($pageFile)) {
382            return file_get_contents($pageFile);
383        }
384
385        return false;
386    }
387
388
389    /**
390     * Find an appropriate template based on the provided text
391     *
392     * Uses ChromaDB to search for the most relevant template based on the content.
393     *
394     * @param string $text The text to use for finding a template
395     * @return array The template ID array or empty array if none found
396     * @throws Exception If an error occurs during the search
397     */
398    private function findTemplate($text) {
399        try {
400            // Create ChromaDB client only if enabled
401            $chromaClient = null;
402            if ($this->getConf('enable_chromadb')) {
403                $chromaClient = new \dokuwiki\plugin\dokullm\ChromaDBClient(
404                    $this->getConf('chroma_host'),
405                    $this->getConf('chroma_port'),
406                    $this->getConf('chroma_tenant'),
407                    $this->getConf('chroma_database'),
408                    $this->getConf('chroma_collection'),
409                    $this->getConf('ollama_host'),
410                    $this->getConf('ollama_port'),
411                    $this->getConf('ollama_embeddings_model')
412                );
413            }
414
415            $client = new \dokuwiki\plugin\dokullm\LlmClient(
416                $this->getConf('api_url'),
417                $this->getConf('api_key'),
418                $this->getConf('model'),
419                $this->getConf('timeout'),
420                $this->getConf('temperature'),
421                $this->getConf('top_p'),
422                $this->getConf('top_k'),
423                $this->getConf('min_p'),
424                $this->getConf('think', false),
425                $this->getConf('profile', 'default'),
426                $chromaClient,
427                $ID
428            );
429
430            // Query ChromaDB for the most relevant template
431            $template = $client->queryChromaDBTemplate($text);
432
433            return $template;
434        } catch (Exception $e) {
435            throw new Exception('Error finding template: ' . $e->getMessage());
436        }
437    }
438
439
440    /**
441     * Handle page save event and send page to ChromaDB
442     *
443     * This method is triggered after a page is saved and sends the page content
444     * to ChromaDB for indexing.
445     *
446     * @param Doku_Event $event The event object
447     * @param mixed $param Additional parameters
448     */
449    public function handlePageSave(Doku_Event $event, $param)
450    {
451        global $ID;
452
453        // Only process if we have a valid page ID
454        if (empty($ID)) {
455            return;
456        }
457
458        // Get the page content
459        $content = rawWiki($ID);
460
461        // Skip empty pages
462        if (empty($content)) {
463            return;
464        }
465
466        try {
467            // Send page to ChromaDB
468            $this->sendPageToChromaDB($ID, $content);
469        } catch (Exception $e) {
470            // Log error but don't stop execution
471            \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $e->getMessage());
472        }
473    }
474
475
476    /**
477     * Send page content to ChromaDB
478     *
479     * @param string $pageId The page ID
480     * @param string $content The page content
481     * @return void
482     */
483    private function sendPageToChromaDB($pageId, $content)
484    {
485        // Skip if ChromaDB is disabled
486        if (!$this->getConf('enable_chromadb')) {
487            return;
488        }
489
490        // Convert page ID to file path format for ChromaDB
491        $filePath = wikiFN($pageId);
492
493        try {
494            // Get configuration values
495            $chromaHost = $this->getConf('chroma_host');
496            $chromaPort = $this->getConf('chroma_port');
497            $chromaTenant = $this->getConf('chroma_tenant');
498            $chromaDatabase = $this->getConf('chroma_database');
499            $ollamaHost = $this->getConf('ollama_host');
500            $ollamaPort = $this->getConf('ollama_port');
501            $ollamaModel = $this->getConf('ollama_embeddings_model');
502
503            // Use the existing ChromaDB client to process the file
504            $chroma = new \dokuwiki\plugin\dokullm\ChromaDBClient(
505                $chromaHost,
506                $chromaPort,
507                $chromaTenant,
508                $chromaDatabase,
509                $this->getConf('chroma_collection'),
510                $ollamaHost,
511                $ollamaPort,
512                $ollamaModel
513            );
514
515            // Use the first part of the document ID as collection name, fallback to 'documents'
516            $idParts = explode(':', $pageId);
517            $collectionName = isset($idParts[0]) && !empty($idParts[0]) ? $idParts[0] : 'documents';
518
519            // Process the file directly
520            $result = $chroma->processSingleFile($filePath, $collectionName, false);
521
522            // Log success or failure
523            if ($result['status'] === 'success') {
524                \dokuwiki\Logger::debug('dokullm: Successfully sent page to ChromaDB: ' . $pageId);
525            } else if ($result['status'] === 'skipped') {
526                \dokuwiki\Logger::debug('dokullm: Skipped sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']);
527            } else {
528                \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']);
529            }
530        } catch (Exception $e) {
531            throw $e;
532        }
533    }
534
535
536   /**
537     * Handler to load page template.
538     *
539     * @param Doku_Event $event  event object by reference
540     * @param mixed      $param  [the parameters passed as fifth argument to register_hook() when this
541     *                           handler was registered]
542     * @return void
543     */
544    public function handleTemplate(Doku_Event &$event, $param) {
545        if (strlen($_REQUEST['copyfrom']) > 0) {
546            $template_id = $_REQUEST['copyfrom'];
547            if (auth_quickaclcheck($template_id) >= AUTH_READ) {
548                $tpl = io_readFile(wikiFN($template_id));
549                if ($this->getConf('replace_id')) {
550                    $id = $event->data['id'];
551                    $tpl = str_replace($template_id, $id, $tpl);
552                }
553                // Add LLM_TEMPLATE metadata if the original page ID contains 'template'
554                if (strpos($template_id, 'template') !== false) {
555                    $tpl = $this->insertMetadataAfterTitle($tpl, '~~LLM_TEMPLATE:' . $template_id . '~~');
556                }
557                $event->data['tpl'] = $tpl;
558                $event->preventDefault();
559            }
560        }
561    }
562
563
564
565   /**
566     * Add 'Copy page' button to page tools, SVG based
567     *
568     * @param Doku_Event $event
569     */
570    public function addCopyPageButton(Doku_Event $event)
571    {
572        global $INFO;
573        if ($event->data['view'] != 'page' || !$this->getConf('show_copy_button')) {
574            return;
575        }
576        if (! $INFO['exists']) {
577            return;
578        }
579        array_splice($event->data['items'], -1, 0, [new \dokuwiki\plugin\dokullm\MenuItem()]);
580    }
581}
582