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