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