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