xref: /plugin/dokullm/action.php (revision 8273dd4798f310cb9522ea2e8ac40fc31b7009d9)
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            $result = $client->process($action, $text, $metadata);
267            echo json_encode(['result' => $result]);
268        } catch (Exception $e) {
269            http_status(500);
270            echo json_encode(['error' => $e->getMessage()]);
271        }
272    }
273
274    /**
275     * Get action definitions from the DokuWiki table at dokullm:profiles:PROFILE
276     *
277     * Parses the table containing action definitions with the following columns:
278     *
279     * - ID: The action identifier, which corresponds to the prompt name
280     * - Label: The text displayed on the button
281     * - Description: A detailed description of the action, used as a tooltip
282     * - Icon: The icon displayed on the button (can be empty)
283     * - Result: The action to perform with the LLM result:
284     *   - show: Display the result in a modal dialog
285     *   - append: Add the result to the end of the current content
286     *   - replace: Replace the selected content with the result
287     *   - insert: Insert the result at the cursor position
288     *
289     * The parsing stops after the first table ends to avoid processing
290     * additional tables that might contain disabled or work-in-progress commands.
291     *
292     * The ID can be either:
293     * - A simple word (e.g., "summary")
294     * - A link to a page in the profile namespace (e.g., "[[.:default:summarize]]")
295     *
296     * For page links, the actual ID is extracted as the last part after the final ':'
297     *
298     * @return array Array of action definitions, each containing:
299     *               - id: string, the action identifier
300     *               - label: string, the button label
301     *               - description: string, the action description
302     *               - icon: string, the icon name
303     *               - result: string, the result handling method
304     */
305    private function getActions()
306    {
307        // Get the content of the profile page
308        $profile = $this->getConf('profile', 'default');
309        $content = $this->getPageContent('dokullm:profiles:' . $profile);
310
311        if ($content === false) {
312            // Return empty list if page doesn't exist
313            return [];
314        }
315
316        // Parse the table from the page content
317        $actions = [];
318        $lines = explode("\n", $content);
319        $inTable = false;
320
321        foreach ($lines as $line) {
322            // Check if this is a table row
323            if (preg_match('/^\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|$/', $line, $matches)) {
324                $inTable = true;
325
326                // Skip header row
327                if (trim($matches[1]) === 'ID' || trim($matches[1]) === 'id') {
328                    continue;
329                }
330
331                // Extract ID from either simple text or page link
332                $rawId = trim($matches[1]);
333                $id = $rawId;
334
335                // Check if ID is a page link in format [[namespace:page]] or [[.:namespace:page]]
336                if (preg_match('/\[\[\.?:?([^\]]+)\]\]/', $rawId, $linkMatches)) {
337                    // Extract the actual page path
338                    $pagePath = $linkMatches[1];
339                    // Get the last part after the final ':' as the ID
340                    $pathParts = explode(':', $pagePath);
341                    $id = end($pathParts);
342                }
343
344                $actions[] = [
345                    'id' => $id,
346                    'label' => trim($matches[2]),
347                    'description' => trim($matches[3]),
348                    'icon' => trim($matches[4]),
349                    'result' => trim($matches[5])
350                ];
351            } else if ($inTable) {
352                // We've exited the table, so stop parsing
353                break;
354            }
355        }
356
357        return $actions;
358    }
359
360    /**
361     * Get the content of a DokuWiki page
362     *
363     * Retrieves the raw content of a DokuWiki page by its ID.
364     * Used for loading template and example page content for context.
365     *
366     * @param string $pageId The page ID to retrieve
367     * @return string|false The page content or false if not found/readable
368     */
369    private function getPageContent($pageId)
370    {
371        // Convert page ID to file path
372        $pageFile = wikiFN($pageId);
373
374        // Check if file exists and is readable
375        if (file_exists($pageFile) && is_readable($pageFile)) {
376            return file_get_contents($pageFile);
377        }
378
379        return false;
380    }
381
382
383    /**
384     * Find an appropriate template based on the provided text
385     *
386     * Uses ChromaDB to search for the most relevant template based on the content.
387     *
388     * @param string $text The text to use for finding a template
389     * @return array The template ID array or empty array if none found
390     * @throws Exception If an error occurs during the search
391     */
392    private function findTemplate($text) {
393        try {
394            // Create ChromaDB client only if enabled
395            $chromaClient = null;
396            if ($this->getConf('enable_chromadb')) {
397                $chromaClient = new \dokuwiki\plugin\dokullm\ChromaDBClient(
398                    $this->getConf('chroma_host'),
399                    $this->getConf('chroma_port'),
400                    $this->getConf('chroma_tenant'),
401                    $this->getConf('chroma_database'),
402                    $this->getConf('chroma_collection'),
403                    $this->getConf('ollama_host'),
404                    $this->getConf('ollama_port'),
405                    $this->getConf('ollama_embeddings_model')
406                );
407            }
408
409            $client = new \dokuwiki\plugin\dokullm\LlmClient(
410                $this->getConf('api_url'),
411                $this->getConf('api_key'),
412                $this->getConf('model'),
413                $this->getConf('timeout'),
414                $this->getConf('temperature'),
415                $this->getConf('top_p'),
416                $this->getConf('top_k'),
417                $this->getConf('min_p'),
418                $this->getConf('think', false),
419                $this->getConf('profile', 'default'),
420                $chromaClient,
421                $ID
422            );
423
424            // Query ChromaDB for the most relevant template
425            $template = $client->queryChromaDBTemplate($text);
426
427            return $template;
428        } catch (Exception $e) {
429            throw new Exception('Error finding template: ' . $e->getMessage());
430        }
431    }
432
433
434    /**
435     * Handle page save event and send page to ChromaDB
436     *
437     * This method is triggered after a page is saved and sends the page content
438     * to ChromaDB for indexing.
439     *
440     * @param Doku_Event $event The event object
441     * @param mixed $param Additional parameters
442     */
443    public function handlePageSave(Doku_Event $event, $param)
444    {
445        global $ID;
446
447        // Only process if we have a valid page ID
448        if (empty($ID)) {
449            return;
450        }
451
452        // Get the page content
453        $content = rawWiki($ID);
454
455        // Skip empty pages
456        if (empty($content)) {
457            return;
458        }
459
460        try {
461            // Send page to ChromaDB
462            $this->sendPageToChromaDB($ID, $content);
463        } catch (Exception $e) {
464            // Log error but don't stop execution
465            \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $e->getMessage());
466        }
467    }
468
469
470    /**
471     * Send page content to ChromaDB
472     *
473     * @param string $pageId The page ID
474     * @param string $content The page content
475     * @return void
476     */
477    private function sendPageToChromaDB($pageId, $content)
478    {
479        // Skip if ChromaDB is disabled
480        if (!$this->getConf('enable_chromadb')) {
481            return;
482        }
483
484        // Convert page ID to file path format for ChromaDB
485        $filePath = wikiFN($pageId);
486
487        try {
488            // Get configuration values
489            $chromaHost = $this->getConf('chroma_host');
490            $chromaPort = $this->getConf('chroma_port');
491            $chromaTenant = $this->getConf('chroma_tenant');
492            $chromaDatabase = $this->getConf('chroma_database');
493            $ollamaHost = $this->getConf('ollama_host');
494            $ollamaPort = $this->getConf('ollama_port');
495            $ollamaModel = $this->getConf('ollama_embeddings_model');
496
497            // Use the existing ChromaDB client to process the file
498            $chroma = new \dokuwiki\plugin\dokullm\ChromaDBClient(
499                $chromaHost,
500                $chromaPort,
501                $chromaTenant,
502                $chromaDatabase,
503                $this->getConf('chroma_collection'),
504                $ollamaHost,
505                $ollamaPort,
506                $ollamaModel
507            );
508
509            // Use the first part of the document ID as collection name, fallback to 'documents'
510            $idParts = explode(':', $pageId);
511            $collectionName = isset($idParts[0]) && !empty($idParts[0]) ? $idParts[0] : 'documents';
512
513            // Process the file directly
514            $result = $chroma->processSingleFile($filePath, $collectionName, false);
515
516            // Log success or failure
517            if ($result['status'] === 'success') {
518                \dokuwiki\Logger::debug('dokullm: Successfully sent page to ChromaDB: ' . $pageId);
519            } else if ($result['status'] === 'skipped') {
520                \dokuwiki\Logger::debug('dokullm: Skipped sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']);
521            } else {
522                \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']);
523            }
524        } catch (Exception $e) {
525            throw $e;
526        }
527    }
528
529
530   /**
531     * Handler to load page template.
532     *
533     * @param Doku_Event $event  event object by reference
534     * @param mixed      $param  [the parameters passed as fifth argument to register_hook() when this
535     *                           handler was registered]
536     * @return void
537     */
538    public function handleTemplate(Doku_Event &$event, $param) {
539        if (strlen($_REQUEST['copyfrom']) > 0) {
540            $template_id = $_REQUEST['copyfrom'];
541            if (auth_quickaclcheck($template_id) >= AUTH_READ) {
542                $tpl = io_readFile(wikiFN($template_id));
543                if ($this->getConf('replace_id')) {
544                    $id = $event->data['id'];
545                    $tpl = str_replace($template_id, $id, $tpl);
546                }
547                // Add LLM_TEMPLATE metadata if the original page ID contains 'template'
548                if (strpos($template_id, 'template') !== false) {
549                    $tpl = $this->insertMetadataAfterTitle($tpl, '~~LLM_TEMPLATE:' . $template_id . '~~');
550                }
551                $event->data['tpl'] = $tpl;
552                $event->preventDefault();
553            }
554        }
555    }
556
557
558
559   /**
560     * Add 'Copy page' button to page tools, SVG based
561     *
562     * @param Doku_Event $event
563     */
564    public function addCopyPageButton(Doku_Event $event)
565    {
566        global $INFO;
567        if ($event->data['view'] != 'page' || !$this->getConf('show_copy_button')) {
568            return;
569        }
570        if (! $INFO['exists']) {
571            return;
572        }
573        array_splice($event->data['items'], -1, 0, [new \dokuwiki\plugin\dokullm\MenuItem()]);
574    }
575}
576