xref: /plugin/dokullm/action.php (revision 01e4fbffba1c3ffb88b36c2670ae6f956fb8dec3)
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 * - language: Language code 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        $client = new \dokuwiki\plugin\dokullm\LlmClient(
192            $this->getConf('api_url'),
193            $this->getConf('api_key'),
194            $this->getConf('model'),
195            $this->getConf('timeout'),
196            $this->getConf('temperature'),
197            $this->getConf('top_p'),
198            $this->getConf('top_k'),
199            $this->getConf('min_p'),
200            $this->getConf('think', false),
201            $this->getConf('language', 'en')
202        );
203        try {
204            switch ($action) {
205                case 'custom':
206                    $result = $client->processCustomPrompt($text, $metadata);
207                default:
208                    $result = $client->process($action, $text, $metadata);
209            }
210            echo json_encode(['result' => $result]);
211        } catch (Exception $e) {
212            http_status(500);
213            echo json_encode(['error' => $e->getMessage()]);
214        }
215    }
216
217    /**
218     * Get action definitions from the DokuWiki table at dokullm:prompts
219     *
220     * Parses the table containing action definitions with columns:
221     * ID, Label, Icon, Action
222     *
223     * Stops parsing after the first table ends to avoid processing
224     * additional tables with disabled or work-in-progress commands.
225     *
226     * @return array Array of action definitions
227     */
228    private function getActions()
229    {
230        // Get the content of the prompts page
231        $content = $this->getPageContent('dokullm:prompts');
232
233        if ($content === false) {
234            // Return empty list if page doesn't exist
235            return [];
236        }
237
238        // Parse the table from the page content
239        $actions = [];
240        $lines = explode("\n", $content);
241        $inTable = false;
242
243        foreach ($lines as $line) {
244            // Check if this is a table row
245            if (preg_match('/^\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|\s*([^\|]+)\s*\|$/', $line, $matches)) {
246                $inTable = true;
247
248                // Skip header row
249                if (trim($matches[1]) === 'ID' || trim($matches[1]) === 'id') {
250                    continue;
251                }
252
253                $actions[] = [
254                    'id' => trim($matches[1]),
255                    'label' => trim($matches[2]),
256                    'description' => trim($matches[3]),
257                    'icon' => trim($matches[4]),
258                    'result' => trim($matches[5])
259                ];
260            } else if ($inTable) {
261                // We've exited the table, so stop parsing
262                break;
263            }
264        }
265
266        return $actions;
267    }
268
269    /**
270     * Get the content of a DokuWiki page
271     *
272     * Retrieves the raw content of a DokuWiki page by its ID.
273     * Used for loading template and example page content for context.
274     *
275     * @param string $pageId The page ID to retrieve
276     * @return string|false The page content or false if not found/readable
277     */
278    private function getPageContent($pageId)
279    {
280        // Convert page ID to file path
281        $pageFile = wikiFN($pageId);
282
283        // Check if file exists and is readable
284        if (file_exists($pageFile) && is_readable($pageFile)) {
285            return file_get_contents($pageFile);
286        }
287
288        return false;
289    }
290
291
292    /**
293     * Find an appropriate template based on the provided text
294     *
295     * Uses ChromaDB to search for the most relevant template based on the content.
296     *
297     * @param string $text The text to use for finding a template
298     * @return array The template ID array or empty array if none found
299     * @throws Exception If an error occurs during the search
300     */
301    private function findTemplate($text) {
302        try {
303            // Get ChromaDB client through the LLM client
304            $client = new \dokuwiki\plugin\dokullm\LlmClient(
305                $this->getConf('api_url'),
306                $this->getConf('api_key'),
307                $this->getConf('model'),
308                $this->getConf('timeout'),
309                $this->getConf('temperature'),
310                $this->getConf('top_p'),
311                $this->getConf('top_k'),
312                $this->getConf('min_p'),
313                $this->getConf('think', false),
314                $this->getConf('language', 'en')
315            );
316
317            // Query ChromaDB for the most relevant template
318            $template = $client->queryChromaDBTemplate($text);
319
320            return $template;
321        } catch (Exception $e) {
322            throw new Exception('Error finding template: ' . $e->getMessage());
323        }
324    }
325
326
327    /**
328     * Handle page save event and send page to ChromaDB
329     *
330     * This method is triggered after a page is saved and sends the page content
331     * to ChromaDB for indexing.
332     *
333     * @param Doku_Event $event The event object
334     * @param mixed $param Additional parameters
335     */
336    public function handlePageSave(Doku_Event $event, $param)
337    {
338        global $ID;
339
340        // Only process if we have a valid page ID
341        if (empty($ID)) {
342            return;
343        }
344
345        // Get the page content
346        $content = rawWiki($ID);
347
348        // Skip empty pages
349        if (empty($content)) {
350            return;
351        }
352
353        try {
354            // Send page to ChromaDB
355            $this->sendPageToChromaDB($ID, $content);
356        } catch (Exception $e) {
357            // Log error but don't stop execution
358            \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $e->getMessage());
359        }
360    }
361
362
363    /**
364     * Send page content to ChromaDB
365     *
366     * @param string $pageId The page ID
367     * @param string $content The page content
368     * @return void
369     */
370    private function sendPageToChromaDB($pageId, $content)
371    {
372        // Convert page ID to file path format for ChromaDB
373        $filePath = wikiFN($pageId);
374
375        try {
376            // Get configuration values
377            $chromaHost = $this->getConf('chroma_host');
378            $chromaPort = $this->getConf('chroma_port');
379            $chromaTenant = $this->getConf('chroma_tenant');
380            $chromaDatabase = $this->getConf('chroma_database');
381            $ollamaHost = $this->getConf('ollama_host');
382            $ollamaPort = $this->getConf('ollama_port');
383            $ollamaModel = $this->getConf('ollama_embeddings_model');
384
385            // Use the existing ChromaDB client to process the file
386            $chroma = new \dokuwiki\plugin\dokullm\ChromaDBClient(
387                $chromaHost,
388                $chromaPort,
389                $chromaTenant,
390                $chromaDatabase,
391                $ollamaHost,
392                $ollamaPort,
393                $ollamaModel
394            );
395
396            // Use the first part of the document ID as collection name, fallback to 'documents'
397            $idParts = explode(':', $pageId);
398            $collectionName = isset($idParts[0]) && !empty($idParts[0]) ? $idParts[0] : 'documents';
399
400            // Process the file directly
401            $result = $chroma->processSingleFile($filePath, $collectionName, false);
402
403            // Log success or failure
404            if ($result['status'] === 'success') {
405                \dokuwiki\Logger::debug('dokullm: Successfully sent page to ChromaDB: ' . $pageId);
406            } else if ($result['status'] === 'skipped') {
407                \dokuwiki\Logger::debug('dokullm: Skipped sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']);
408            } else {
409                \dokuwiki\Logger::error('dokullm: Error sending page to ChromaDB: ' . $pageId . ' - ' . $result['message']);
410            }
411        } catch (Exception $e) {
412            throw $e;
413        }
414    }
415
416
417   /**
418     * Handler to load page template.
419     *
420     * @param Doku_Event $event  event object by reference
421     * @param mixed      $param  [the parameters passed as fifth argument to register_hook() when this
422     *                           handler was registered]
423     * @return void
424     */
425    public function handleTemplate(Doku_Event &$event, $param) {
426        if (strlen($_REQUEST['copyfrom']) > 0) {
427            $template_id = $_REQUEST['copyfrom'];
428            if (auth_quickaclcheck($template_id) >= AUTH_READ) {
429                $tpl = io_readFile(wikiFN($template_id));
430                if ($this->getConf('replace_id')) {
431                    $id = $event->data['id'];
432                    $tpl = str_replace($template_id, $id, $tpl);
433                }
434                // Add LLM_TEMPLATE metadata if the original page ID contains 'template'
435                if (strpos($template_id, 'template') !== false) {
436                    $tpl = '~~LLM_TEMPLATE:' . $template_id . '~~' . "\n" . $tpl;
437                }
438                $event->data['tpl'] = $tpl;
439                $event->preventDefault();
440            }
441        }
442    }
443
444
445
446   /**
447     * Add 'Copy page' button to page tools, SVG based
448     *
449     * @param Doku_Event $event
450     */
451    public function addCopyPageButton(Doku_Event $event)
452    {
453        global $INFO;
454        if ($event->data['view'] != 'page' || !$this->getConf('show_copy_button')) {
455            return;
456        }
457        if (! $INFO['exists']) {
458            return;
459        }
460        array_splice($event->data['items'], -1, 0, [new \dokuwiki\plugin\dokullm\MenuItem()]);
461    }
462}
463