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