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