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