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