xref: /plugin/aichat/cli.php (revision dc355d5718db432124322cbaaff5af096c20e833)
1<?php
2
3use dokuwiki\Extension\CLIPlugin;
4use dokuwiki\plugin\aichat\Chunk;
5use dokuwiki\Search\Indexer;
6use splitbrain\phpcli\Colors;
7use splitbrain\phpcli\Options;
8use splitbrain\phpcli\TableFormatter;
9
10/**
11 * DokuWiki Plugin aichat (CLI Component)
12 *
13 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
14 * @author  Andreas Gohr <gohr@cosmocode.de>
15 */
16class cli_plugin_aichat extends CLIPlugin
17{
18    /** @var helper_plugin_aichat */
19    protected $helper;
20
21    public function __construct($autocatch = true)
22    {
23        parent::__construct($autocatch);
24        $this->helper = plugin_load('helper', 'aichat');
25        $this->helper->setLogger($this);
26    }
27
28    /** @inheritDoc */
29    protected function setup(Options $options)
30    {
31        $options->useCompactHelp();
32
33        $options->setHelp(
34            'Manage and query the AI chatbot data. Please note that calls to your LLM provider will be made. ' .
35            'This may incur costs.'
36        );
37
38        $options->registerCommand(
39            'embed',
40            'Create embeddings for all pages. This skips pages that already have embeddings'
41        );
42        $options->registerOption(
43            'clear',
44            'Clear all existing embeddings before creating new ones',
45            'c',
46            false,
47            'embed'
48        );
49
50        $options->registerCommand('maintenance', 'Run storage maintenance. Refert to the documentation for details.');
51
52        $options->registerCommand('similar', 'Search for similar pages');
53        $options->registerArgument('query', 'Look up chunks similar to this query', true, 'similar');
54
55        $options->registerCommand('ask', 'Ask a question');
56        $options->registerArgument('question', 'The question to ask', true, 'ask');
57
58        $options->registerCommand('chat', 'Start an interactive chat session');
59
60        $options->registerCommand('info', 'Get Info about the vector storage');
61
62        $options->registerCommand('split', 'Split a page into chunks (for debugging)');
63        $options->registerArgument('page', 'The page to split', true, 'split');
64
65        $options->registerCommand('page', 'Check if chunks for a given page are available (for debugging)');
66        $options->registerArgument('page', 'The page to check', true, 'page');
67        $options->registerOption('dump', 'Dump the chunks', 'd', false, 'page');
68
69        $options->registerCommand('tsv', 'Create TSV files for visualizing at http://projector.tensorflow.org/' .
70            ' Not supported on all storages.');
71        $options->registerArgument('vector.tsv', 'The vector file', false, 'tsv');
72        $options->registerArgument('meta.tsv', 'The meta file', false, 'tsv');
73    }
74
75    /** @inheritDoc */
76    protected function main(Options $options)
77    {
78        ini_set('memory_limit', -1);
79        switch ($options->getCmd()) {
80            case 'embed':
81                $this->createEmbeddings($options->getOpt('clear'));
82                break;
83            case 'maintenance':
84                $this->runMaintenance();
85                break;
86            case 'similar':
87                $this->similar($options->getArgs()[0]);
88                break;
89            case 'ask':
90                $this->ask($options->getArgs()[0]);
91                break;
92            case 'chat':
93                $this->chat();
94                break;
95            case 'split':
96                $this->split($options->getArgs()[0]);
97                break;
98            case 'page':
99                $this->page($options->getArgs()[0], $options->getOpt('dump'));
100                break;
101            case 'info':
102                $this->showinfo();
103                break;
104            case 'tsv':
105                $args = $options->getArgs();
106                $vector = $args[0] ?? 'vector.tsv';
107                $meta = $args[1] ?? 'meta.tsv';
108                $this->tsv($vector, $meta);
109                break;
110            default:
111                echo $options->help();
112        }
113    }
114
115    /**
116     * @return void
117     */
118    protected function showinfo()
119    {
120        $stats = [
121            'model' => $this->getConf('model'),
122        ];
123        $stats = array_merge($stats, $this->helper->getStorage()->statistics());
124        $this->printTable($stats);
125    }
126
127    /**
128     * Print key value data as tabular data
129     *
130     * @param array $data
131     * @param int $level
132     * @return void
133     */
134    protected function printTable($data, $level = 0)
135    {
136        $tf = new TableFormatter($this->colors);
137        foreach ($data as $key => $value) {
138            if (is_array($value)) {
139                echo $tf->format(
140                    [$level * 2, 15, '*'],
141                    ['', $key, ''],
142                    [Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE]
143                );
144                $this->printTable($value, $level + 1);
145            } else {
146                echo $tf->format(
147                    [$level * 2, 15, '*'],
148                    ['', $key, $value],
149                    [Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTGRAY]
150                );
151            }
152        }
153    }
154
155    /**
156     * Check chunk availability for a given page
157     *
158     * @param string $page
159     * @return void
160     */
161    protected function page($page, $dump = false)
162    {
163        $indexer = new Indexer();
164        $pages = $indexer->getPages();
165        $pos = array_search(cleanID($page), $pages);
166
167        if ($pos === false) {
168            $this->error('Page not found');
169            return;
170        }
171
172        $storage = $this->helper->getStorage();
173        $chunks = $storage->getPageChunks($page, $pos * 100);
174        if ($chunks) {
175            $this->success('Found ' . count($chunks) . ' chunks');
176            if ($dump) {
177                echo json_encode($chunks, JSON_PRETTY_PRINT);
178            }
179        } else {
180            $this->error('No chunks found');
181        }
182    }
183
184    /**
185     * Split the given page into chunks and print them
186     *
187     * @param string $page
188     * @return void
189     * @throws Exception
190     */
191    protected function split($page)
192    {
193        $text = rawWiki($page);
194        $chunks = $this->helper->getEmbeddings()->splitIntoChunks($text);
195        foreach ($chunks as $chunk) {
196            echo $chunk;
197            echo "\n";
198            $this->colors->ptln('--------------------------------', Colors::C_LIGHTPURPLE);
199        }
200        $this->success('Split into ' . count($chunks) . ' chunks');
201    }
202
203    /**
204     * Interactive Chat Session
205     *
206     * @return void
207     * @throws Exception
208     */
209    protected function chat()
210    {
211        $history = [];
212        while ($q = $this->readLine('Your Question')) {
213            $this->helper->getModel()->resetUsageStats();
214            $result = $this->helper->askChatQuestion($q, $history);
215            $this->colors->ptln("Interpretation: {$result['question']}", Colors::C_LIGHTPURPLE);
216            $history[] = [$result['question'], $result['answer']];
217            $this->printAnswer($result);
218        }
219    }
220
221    /**
222     * Handle a single, standalone question
223     *
224     * @param string $query
225     * @return void
226     * @throws Exception
227     */
228    protected function ask($query)
229    {
230        $result = $this->helper->askQuestion($query);
231        $this->printAnswer($result);
232    }
233
234    /**
235     * Get the pages that are similar to the query
236     *
237     * @param string $query
238     * @return void
239     */
240    protected function similar($query)
241    {
242        $langlimit = $this->helper->getLanguageLimit();
243        if ($langlimit) {
244            $this->info('Limiting results to {lang}', ['lang' => $langlimit]);
245        }
246
247        $sources = $this->helper->getEmbeddings()->getSimilarChunks($query, $langlimit);
248        $this->printSources($sources);
249    }
250
251    /**
252     * Run the maintenance tasks
253     *
254     * @return void
255     */
256    protected function runMaintenance()
257    {
258        $start = time();
259        $this->helper->getStorage()->runMaintenance();
260        $this->notice('Peak memory used: {memory}', ['memory' => filesize_h(memory_get_peak_usage(true))]);
261        $this->notice('Spent time: {time}min', ['time' => round((time() - $start) / 60, 2)]);
262    }
263
264    /**
265     * Recreate chunks and embeddings for all pages
266     *
267     * @return void
268     * @todo make skip regex configurable
269     */
270    protected function createEmbeddings($clear)
271    {
272        $start = time();
273        $this->helper->getEmbeddings()->createNewIndex('/(^|:)(playground|sandbox)(:|$)/', $clear);
274        $this->notice('Peak memory used: {memory}', ['memory' => filesize_h(memory_get_peak_usage(true))]);
275        $this->notice('Spent time: {time}min', ['time' => round((time() - $start) / 60, 2)]);
276    }
277
278    /**
279     * Dump TSV files for debugging
280     *
281     * @return void
282     */
283    protected function tsv($vector, $meta)
284    {
285
286        $storage = $this->helper->getStorage();
287        $storage->dumpTSV($vector, $meta);
288        $this->success('written to ' . $vector . ' and ' . $meta);
289    }
290
291    /**
292     * Print the given detailed answer in a nice way
293     *
294     * @param array $answer
295     * @return void
296     */
297    protected function printAnswer($answer)
298    {
299        $this->colors->ptln($answer['answer'], Colors::C_LIGHTCYAN);
300        echo "\n";
301        $this->printSources($answer['sources']);
302        echo "\n";
303        $this->printUsage();
304    }
305
306    /**
307     * Print the given sources
308     *
309     * @param Chunk[] $sources
310     * @return void
311     */
312    protected function printSources($sources)
313    {
314        foreach ($sources as $source) {
315            /** @var Chunk $source */
316            $this->colors->ptln(
317                "\t" . $source->getPage() . ' ' . $source->getId() . ' (' . $source->getScore() . ')',
318                Colors::C_LIGHTBLUE
319            );
320        }
321    }
322
323    /**
324     * Print the usage statistics for OpenAI
325     *
326     * @return void
327     */
328    protected function printUsage()
329    {
330        $this->info(
331            'Made {requests} requests in {time}s to Model. Used {tokens} tokens for about ${cost}.',
332            $this->helper->getModel()->getUsageStats()
333        );
334    }
335
336    /**
337     * Interactively ask for a value from the user
338     *
339     * @param string $prompt
340     * @return string
341     */
342    protected function readLine($prompt)
343    {
344        $value = '';
345
346        while ($value === '') {
347            echo $prompt;
348            echo ': ';
349
350            $fh = fopen('php://stdin', 'r');
351            $value = trim(fgets($fh));
352            fclose($fh);
353        }
354
355        return $value;
356    }
357}
358