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. Refer 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('models', 'List available models'); 61 62 $options->registerCommand('info', 'Get Info about the vector storage and other stats'); 63 64 $options->registerCommand('split', 'Split a page into chunks (for debugging)'); 65 $options->registerArgument('page', 'The page to split', true, 'split'); 66 67 $options->registerCommand('page', 'Check if chunks for a given page are available (for debugging)'); 68 $options->registerArgument('page', 'The page to check', true, 'page'); 69 $options->registerOption('dump', 'Dump the chunks', 'd', false, 'page'); 70 71 $options->registerCommand('tsv', 'Create TSV files for visualizing at http://projector.tensorflow.org/' . 72 ' Not supported on all storages.'); 73 $options->registerArgument('vector.tsv', 'The vector file', false, 'tsv'); 74 $options->registerArgument('meta.tsv', 'The meta file', false, 'tsv'); 75 } 76 77 /** @inheritDoc */ 78 protected function main(Options $options) 79 { 80 $this->loadConfig(); 81 ini_set('memory_limit', -1); 82 switch ($options->getCmd()) { 83 case 'embed': 84 $this->createEmbeddings($options->getOpt('clear')); 85 break; 86 case 'maintenance': 87 $this->runMaintenance(); 88 break; 89 case 'similar': 90 $this->similar($options->getArgs()[0]); 91 break; 92 case 'ask': 93 $this->ask($options->getArgs()[0]); 94 break; 95 case 'chat': 96 $this->chat(); 97 break; 98 case 'models': 99 $this->models(); 100 break; 101 case 'split': 102 $this->split($options->getArgs()[0]); 103 break; 104 case 'page': 105 $this->page($options->getArgs()[0], $options->getOpt('dump')); 106 break; 107 case 'info': 108 $this->showinfo(); 109 break; 110 case 'tsv': 111 $args = $options->getArgs(); 112 $vector = $args[0] ?? 'vector.tsv'; 113 $meta = $args[1] ?? 'meta.tsv'; 114 $this->tsv($vector, $meta); 115 break; 116 default: 117 echo $options->help(); 118 } 119 } 120 121 /** 122 * @return void 123 */ 124 protected function showinfo() 125 { 126 $stats = [ 127 'chat model' => $this->getConf('chatmodel'), 128 'embed model' => $this->getConf('embedmodel'), 129 ]; 130 $stats = array_merge( 131 $stats, 132 array_map('dformat', $this->helper->getRunData()), 133 $this->helper->getStorage()->statistics() 134 ); 135 $this->printTable($stats); 136 } 137 138 /** 139 * Print key value data as tabular data 140 * 141 * @param array $data 142 * @param int $level 143 * @return void 144 */ 145 protected function printTable($data, $level = 0) 146 { 147 $tf = new TableFormatter($this->colors); 148 foreach ($data as $key => $value) { 149 if (is_array($value)) { 150 echo $tf->format( 151 [$level * 2, 20, '*'], 152 ['', $key, ''], 153 [Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE] 154 ); 155 $this->printTable($value, $level + 1); 156 } else { 157 echo $tf->format( 158 [$level * 2, 20, '*'], 159 ['', $key, $value], 160 [Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTGRAY] 161 ); 162 } 163 } 164 } 165 166 /** 167 * Check chunk availability for a given page 168 * 169 * @param string $page 170 * @return void 171 */ 172 protected function page($page, $dump = false) 173 { 174 $indexer = new Indexer(); 175 $pages = $indexer->getPages(); 176 $pos = array_search(cleanID($page), $pages); 177 178 if ($pos === false) { 179 $this->error('Page not found'); 180 return; 181 } 182 183 $storage = $this->helper->getStorage(); 184 $chunks = $storage->getPageChunks($page, $pos * 100); 185 if ($chunks) { 186 $this->success('Found ' . count($chunks) . ' chunks'); 187 if ($dump) { 188 echo json_encode($chunks, JSON_PRETTY_PRINT); 189 } 190 } else { 191 $this->error('No chunks found'); 192 } 193 } 194 195 /** 196 * Split the given page into chunks and print them 197 * 198 * @param string $page 199 * @return void 200 * @throws Exception 201 */ 202 protected function split($page) 203 { 204 $text = rawWiki($page); 205 $chunks = $this->helper->getEmbeddings()->splitIntoChunks($text); 206 foreach ($chunks as $chunk) { 207 echo $chunk; 208 echo "\n"; 209 $this->colors->ptln('--------------------------------', Colors::C_LIGHTPURPLE); 210 } 211 $this->success('Split into ' . count($chunks) . ' chunks'); 212 } 213 214 /** 215 * Interactive Chat Session 216 * 217 * @return void 218 * @throws Exception 219 */ 220 protected function chat() 221 { 222 if ($this->loglevel['debug']['enabled']) { 223 $this->helper->getChatModel()->setDebug(true); 224 } 225 226 $history = []; 227 while ($q = $this->readLine('Your Question')) { 228 $this->helper->getChatModel()->resetUsageStats(); 229 $result = $this->helper->askChatQuestion($q, $history); 230 $this->colors->ptln("Interpretation: {$result['question']}", Colors::C_LIGHTPURPLE); 231 $history[] = [$result['question'], $result['answer']]; 232 $this->printAnswer($result); 233 } 234 } 235 236 protected function models() 237 { 238 $result = [ 239 'chat' => [], 240 'embedding' => [], 241 ]; 242 243 244 $jsons = glob(__DIR__ . '/Model/*/models.json'); 245 foreach ($jsons as $json) { 246 $models = json_decode(file_get_contents($json), true); 247 foreach ($models as $type => $model) { 248 $namespace = basename(dirname($json)); 249 foreach ($model as $name => $info) { 250 251 252 $class = '\\dokuwiki\\plugin\\aichat\\Model\\' . $namespace . '\\' . ucfirst($type) . 'Model'; 253 try { 254 new $class($name, $this->conf); 255 $info['confok'] = true; 256 } catch (Exception $e) { 257 $info['confok'] = false; 258 } 259 260 $result[$type]["$namespace $name"] = $info; 261 } 262 } 263 } 264 265 $td = new TableFormatter($this->colors); 266 $cols = [30, 20, 20, '*']; 267 echo "==== Chat Models ====\n\n"; 268 echo $td->format( 269 $cols, 270 ['Model', 'Token Limits', 'Price USD/M', 'Description'], 271 [Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE] 272 ); 273 foreach ($result['chat'] as $name => $info) { 274 echo $td->format( 275 $cols, 276 [ 277 $name, 278 sprintf(" In: %7d\nOut: %7d", $info['inputTokens'], $info['outputTokens']), 279 sprintf(" In: %.2f\nOut: %.2f", $info['inputTokenPrice'], $info['outputTokenPrice']), 280 $info['description']."\n" 281 ], 282 [ 283 $info['confok'] ? Colors::C_LIGHTGREEN : Colors::C_LIGHTRED, 284 ] 285 ); 286 } 287 288 $cols = [30, 10, 10, 10, '*']; 289 echo "==== Embedding Models ====\n\n"; 290 echo $td->format( 291 $cols, 292 ['Model', 'Token Limits', 'Price USD/M', 'Dimensions', 'Description'], 293 [Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE] 294 ); 295 foreach ($result['embedding'] as $name => $info) { 296 echo $td->format( 297 $cols, 298 [ 299 $name, 300 sprintf("%7d", $info['inputTokens']), 301 sprintf("%.2f", $info['inputTokenPrice']), 302 $info['dimensions'], 303 $info['description']."\n" 304 ], 305 [ 306 $info['confok'] ? Colors::C_LIGHTGREEN : Colors::C_LIGHTRED, 307 ] 308 ); 309 } 310 311 $this->colors->ptln('Current prices may differ', Colors::C_RED); 312 } 313 314 /** 315 * Handle a single, standalone question 316 * 317 * @param string $query 318 * @return void 319 * @throws Exception 320 */ 321 protected function ask($query) 322 { 323 if ($this->loglevel['debug']['enabled']) { 324 $this->helper->getChatModel()->setDebug(true); 325 } 326 327 $result = $this->helper->askQuestion($query); 328 $this->printAnswer($result); 329 } 330 331 /** 332 * Get the pages that are similar to the query 333 * 334 * @param string $query 335 * @return void 336 */ 337 protected function similar($query) 338 { 339 $langlimit = $this->helper->getLanguageLimit(); 340 if ($langlimit) { 341 $this->info('Limiting results to {lang}', ['lang' => $langlimit]); 342 } 343 344 $sources = $this->helper->getEmbeddings()->getSimilarChunks($query, $langlimit); 345 $this->printSources($sources); 346 } 347 348 /** 349 * Run the maintenance tasks 350 * 351 * @return void 352 */ 353 protected function runMaintenance() 354 { 355 $start = time(); 356 $this->helper->getStorage()->runMaintenance(); 357 $this->notice('Peak memory used: {memory}', ['memory' => filesize_h(memory_get_peak_usage(true))]); 358 $this->notice('Spent time: {time}min', ['time' => round((time() - $start) / 60, 2)]); 359 360 $data = $this->helper->getRunData(); 361 $data['maintenance ran at'] = time(); 362 $this->helper->setRunData($data); 363 } 364 365 /** 366 * Recreate chunks and embeddings for all pages 367 * 368 * @return void 369 */ 370 protected function createEmbeddings($clear) 371 { 372 [$skipRE, $matchRE] = $this->getRegexps(); 373 374 $start = time(); 375 $this->helper->getEmbeddings()->createNewIndex($skipRE, $matchRE, $clear); 376 $this->notice('Peak memory used: {memory}', ['memory' => filesize_h(memory_get_peak_usage(true))]); 377 $this->notice('Spent time: {time}min', ['time' => round((time() - $start) / 60, 2)]); 378 379 $data = $this->helper->getRunData(); 380 $data['embed ran at'] = time(); 381 $this->helper->setRunData($data); 382 } 383 384 /** 385 * Dump TSV files for debugging 386 * 387 * @return void 388 */ 389 protected function tsv($vector, $meta) 390 { 391 392 $storage = $this->helper->getStorage(); 393 $storage->dumpTSV($vector, $meta); 394 $this->success('written to ' . $vector . ' and ' . $meta); 395 } 396 397 /** 398 * Print the given detailed answer in a nice way 399 * 400 * @param array $answer 401 * @return void 402 */ 403 protected function printAnswer($answer) 404 { 405 $this->colors->ptln($answer['answer'], Colors::C_LIGHTCYAN); 406 echo "\n"; 407 $this->printSources($answer['sources']); 408 echo "\n"; 409 $this->printUsage(); 410 } 411 412 /** 413 * Print the given sources 414 * 415 * @param Chunk[] $sources 416 * @return void 417 */ 418 protected function printSources($sources) 419 { 420 foreach ($sources as $source) { 421 /** @var Chunk $source */ 422 $this->colors->ptln( 423 "\t" . $source->getPage() . ' ' . $source->getId() . ' (' . $source->getScore() . ')', 424 Colors::C_LIGHTBLUE 425 ); 426 } 427 } 428 429 /** 430 * Print the usage statistics for OpenAI 431 * 432 * @return void 433 */ 434 protected function printUsage() 435 { 436 $this->info( 437 'Made {requests} requests in {time}s to Model. Used {tokens} tokens for about ${cost}.', 438 $this->helper->getChatModel()->getUsageStats() 439 ); 440 } 441 442 /** 443 * Interactively ask for a value from the user 444 * 445 * @param string $prompt 446 * @return string 447 */ 448 protected function readLine($prompt) 449 { 450 $value = ''; 451 452 while ($value === '') { 453 echo $prompt; 454 echo ': '; 455 456 $fh = fopen('php://stdin', 'r'); 457 $value = trim(fgets($fh)); 458 fclose($fh); 459 } 460 461 return $value; 462 } 463 464 /** 465 * Read the skip and match regex from the config 466 * 467 * Ensures the regular expressions are valid 468 * 469 * @return string[] [$skipRE, $matchRE] 470 */ 471 protected function getRegexps() 472 { 473 $skip = $this->getConf('skipRegex'); 474 $skipRE = ''; 475 $match = $this->getConf('matchRegex'); 476 $matchRE = ''; 477 478 if ($skip) { 479 $skipRE = '/' . $skip . '/'; 480 if (@preg_match($skipRE, '') === false) { 481 $this->error(preg_last_error_msg()); 482 $this->error('Invalid regular expression in $conf[\'skipRegex\']. Ignored.'); 483 $skipRE = ''; 484 } else { 485 $this->success('Skipping pages matching ' . $skipRE); 486 } 487 } 488 489 if ($match) { 490 $matchRE = '/' . $match . '/'; 491 if (@preg_match($matchRE, '') === false) { 492 $this->error(preg_last_error_msg()); 493 $this->error('Invalid regular expression in $conf[\'matchRegex\']. Ignored.'); 494 $matchRE = ''; 495 } else { 496 $this->success('Only indexing pages matching ' . $matchRE); 497 } 498 } 499 return [$skipRE, $matchRE]; 500 } 501} 502