xref: /plugin/aichat/cli.php (revision 5284515d807f1a81ab1cc7dbdd445bd2cfbb2a16)
18817535bSAndreas Gohr<?php
28817535bSAndreas Gohr
3bddd899cSAndreas Gohruse dokuwiki\plugin\aichat\backend\Chunk;
4c4584168SAndreas Gohruse splitbrain\phpcli\Colors;
58817535bSAndreas Gohruse splitbrain\phpcli\Options;
68817535bSAndreas Gohr
78817535bSAndreas Gohr
88817535bSAndreas Gohr/**
98817535bSAndreas Gohr * DokuWiki Plugin aichat (CLI Component)
108817535bSAndreas Gohr *
118817535bSAndreas Gohr * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
128817535bSAndreas Gohr * @author  Andreas Gohr <gohr@cosmocode.de>
138817535bSAndreas Gohr */
148817535bSAndreas Gohrclass cli_plugin_aichat extends \dokuwiki\Extension\CLIPlugin
158817535bSAndreas Gohr{
160337f47fSAndreas Gohr    /** @var helper_plugin_aichat */
170337f47fSAndreas Gohr    protected $helper;
180337f47fSAndreas Gohr
190337f47fSAndreas Gohr    public function __construct($autocatch = true)
200337f47fSAndreas Gohr    {
210337f47fSAndreas Gohr        parent::__construct($autocatch);
220337f47fSAndreas Gohr        $this->helper = plugin_load('helper', 'aichat');
232ecc089aSAndreas Gohr        $this->helper->getEmbeddings()->setLogger($this);
240337f47fSAndreas Gohr    }
250337f47fSAndreas Gohr
268817535bSAndreas Gohr
278817535bSAndreas Gohr    /** @inheritDoc */
288817535bSAndreas Gohr    protected function setup(Options $options)
298817535bSAndreas Gohr    {
30bddd899cSAndreas Gohr        $options->useCompactHelp();
31bddd899cSAndreas Gohr
32*5284515dSAndreas Gohr        $options->setHelp(
33*5284515dSAndreas Gohr            'Manage and query the AI chatbot data. Please note that calls to your LLM provider will be made. ' .
34*5284515dSAndreas Gohr            'This may incur costs.'
35*5284515dSAndreas Gohr        );
368817535bSAndreas Gohr
37*5284515dSAndreas Gohr        $options->registerCommand(
38*5284515dSAndreas Gohr            'embed',
39*5284515dSAndreas Gohr            'Create embeddings for all pages. This skips pages that already have embeddings'
40*5284515dSAndreas Gohr        );
41*5284515dSAndreas Gohr        $options->registerOption(
42*5284515dSAndreas Gohr            'clear',
43*5284515dSAndreas Gohr            'Clear all existing embeddings before creating new ones',
44*5284515dSAndreas Gohr            'c', false, 'embed'
45*5284515dSAndreas Gohr        );
468817535bSAndreas Gohr
478817535bSAndreas Gohr        $options->registerCommand('similar', 'Search for similar pages');
488817535bSAndreas Gohr        $options->registerArgument('query', 'Look up chunks similar to this query', true, 'similar');
498817535bSAndreas Gohr
508817535bSAndreas Gohr        $options->registerCommand('ask', 'Ask a question');
518817535bSAndreas Gohr        $options->registerArgument('question', 'The question to ask', true, 'ask');
52c4584168SAndreas Gohr
53c4584168SAndreas Gohr        $options->registerCommand('chat', 'Start an interactive chat session');
54ad38c5fdSAndreas Gohr
55ad38c5fdSAndreas Gohr        $options->registerCommand('split', 'Split a page into chunks (for debugging)');
56ad38c5fdSAndreas Gohr        $options->registerArgument('page', 'The page to split', true, 'split');
575786be46SAndreas Gohr
58bddd899cSAndreas Gohr        $options->registerCommand('info', 'Get Info about the vector storage');
598817535bSAndreas Gohr    }
608817535bSAndreas Gohr
618817535bSAndreas Gohr    /** @inheritDoc */
628817535bSAndreas Gohr    protected function main(Options $options)
638817535bSAndreas Gohr    {
648817535bSAndreas Gohr        switch ($options->getCmd()) {
658817535bSAndreas Gohr
668817535bSAndreas Gohr            case 'embed':
67*5284515dSAndreas Gohr                $this->createEmbeddings($options->getOpt('clear'));
688817535bSAndreas Gohr                break;
698817535bSAndreas Gohr            case 'similar':
708817535bSAndreas Gohr                $this->similar($options->getArgs()[0]);
718817535bSAndreas Gohr                break;
727552f1aaSAndreas Gohr            case 'ask':
737552f1aaSAndreas Gohr                $this->ask($options->getArgs()[0]);
747552f1aaSAndreas Gohr                break;
75c4584168SAndreas Gohr            case 'chat':
76c4584168SAndreas Gohr                $this->chat();
77c4584168SAndreas Gohr                break;
78ad38c5fdSAndreas Gohr            case 'split':
79ad38c5fdSAndreas Gohr                $this->split($options->getArgs()[0]);
80ad38c5fdSAndreas Gohr                break;
815786be46SAndreas Gohr            case 'info':
825786be46SAndreas Gohr                $this->treeinfo();
835786be46SAndreas Gohr                break;
848817535bSAndreas Gohr            default:
858817535bSAndreas Gohr                echo $options->help();
868817535bSAndreas Gohr        }
878817535bSAndreas Gohr    }
888817535bSAndreas Gohr
89c4584168SAndreas Gohr    /**
905786be46SAndreas Gohr     * @return void
915786be46SAndreas Gohr     */
925786be46SAndreas Gohr    protected function treeinfo()
935786be46SAndreas Gohr    {
947ee8b02dSAndreas Gohr        $stats = $this->helper->getEmbeddings()->getStorage()->statistics();
957ee8b02dSAndreas Gohr        foreach ($stats as $key => $value) {
967ee8b02dSAndreas Gohr            echo $key . ': ' . $value . "\n";
977ee8b02dSAndreas Gohr        }
985786be46SAndreas Gohr    }
995786be46SAndreas Gohr
1005786be46SAndreas Gohr    /**
101ad38c5fdSAndreas Gohr     * Split the given page into chunks and print them
102ad38c5fdSAndreas Gohr     *
103ad38c5fdSAndreas Gohr     * @param string $page
104ad38c5fdSAndreas Gohr     * @return void
105ad38c5fdSAndreas Gohr     * @throws Exception
106ad38c5fdSAndreas Gohr     */
107ad38c5fdSAndreas Gohr    protected function split($page)
108ad38c5fdSAndreas Gohr    {
109ad38c5fdSAndreas Gohr        $text = rawWiki($page);
110ad38c5fdSAndreas Gohr        $chunks = $this->helper->getEmbeddings()->splitIntoChunks($text);
111ad38c5fdSAndreas Gohr        foreach ($chunks as $chunk) {
112ad38c5fdSAndreas Gohr            echo $chunk;
113ad38c5fdSAndreas Gohr            echo "\n";
114ad38c5fdSAndreas Gohr            $this->colors->ptln('--------------------------------', Colors::C_LIGHTPURPLE);
115ad38c5fdSAndreas Gohr        }
116ad38c5fdSAndreas Gohr        $this->success('Split into ' . count($chunks) . ' chunks');
117ad38c5fdSAndreas Gohr    }
118ad38c5fdSAndreas Gohr
119ad38c5fdSAndreas Gohr    /**
120c4584168SAndreas Gohr     * Interactive Chat Session
121c4584168SAndreas Gohr     *
122c4584168SAndreas Gohr     * @return void
123c4584168SAndreas Gohr     * @throws Exception
124c4584168SAndreas Gohr     */
125c4584168SAndreas Gohr    protected function chat()
126c4584168SAndreas Gohr    {
127c4584168SAndreas Gohr        $history = [];
128c4584168SAndreas Gohr        while ($q = $this->readLine('Your Question')) {
129c4584168SAndreas Gohr            if ($history) {
1300337f47fSAndreas Gohr                $question = $this->helper->rephraseChatQuestion($q, $history);
131c4584168SAndreas Gohr                $this->colors->ptln("Interpretation: $question", Colors::C_LIGHTPURPLE);
132c4584168SAndreas Gohr            } else {
133c4584168SAndreas Gohr                $question = $q;
134c4584168SAndreas Gohr            }
1350337f47fSAndreas Gohr            $result = $this->helper->askQuestion($question);
136c4584168SAndreas Gohr            $history[] = [$q, $result['answer']];
137c4584168SAndreas Gohr            $this->printAnswer($result);
138c4584168SAndreas Gohr        }
139c4584168SAndreas Gohr    }
140c4584168SAndreas Gohr
141c4584168SAndreas Gohr    /**
142c4584168SAndreas Gohr     * Print the given detailed answer in a nice way
143c4584168SAndreas Gohr     *
144c4584168SAndreas Gohr     * @param array $answer
145c4584168SAndreas Gohr     * @return void
146c4584168SAndreas Gohr     */
147c4584168SAndreas Gohr    protected function printAnswer($answer)
148c4584168SAndreas Gohr    {
149c4584168SAndreas Gohr        $this->colors->ptln($answer['answer'], Colors::C_LIGHTCYAN);
150c4584168SAndreas Gohr        echo "\n";
151c4584168SAndreas Gohr        foreach ($answer['sources'] as $source) {
152bddd899cSAndreas Gohr            /** @var Chunk $source */
153bddd899cSAndreas Gohr            $this->colors->ptln("\t" . $source->getPage(), Colors::C_LIGHTBLUE);
154c4584168SAndreas Gohr        }
155c4584168SAndreas Gohr        echo "\n";
156c4584168SAndreas Gohr    }
157c4584168SAndreas Gohr
158c4584168SAndreas Gohr    /**
159c4584168SAndreas Gohr     * Handle a single, standalone question
160c4584168SAndreas Gohr     *
161c4584168SAndreas Gohr     * @param string $query
162c4584168SAndreas Gohr     * @return void
163c4584168SAndreas Gohr     * @throws Exception
164c4584168SAndreas Gohr     */
165c4584168SAndreas Gohr    protected function ask($query)
166c4584168SAndreas Gohr    {
1670337f47fSAndreas Gohr        $result = $this->helper->askQuestion($query);
168c4584168SAndreas Gohr        $this->printAnswer($result);
1697552f1aaSAndreas Gohr    }
1707552f1aaSAndreas Gohr
171c4584168SAndreas Gohr    /**
172c4584168SAndreas Gohr     * Get the pages that are similar to the query
173c4584168SAndreas Gohr     *
174c4584168SAndreas Gohr     * @param string $query
175c4584168SAndreas Gohr     * @return void
176c4584168SAndreas Gohr     */
1778817535bSAndreas Gohr    protected function similar($query)
1788817535bSAndreas Gohr    {
1790337f47fSAndreas Gohr        $sources = $this->helper->getEmbeddings()->getSimilarChunks($query);
180c4584168SAndreas Gohr        foreach ($sources as $source) {
1817ee8b02dSAndreas Gohr            $this->colors->ptln($source->getPage(), Colors::C_LIGHTBLUE);
182c4584168SAndreas Gohr        }
1838817535bSAndreas Gohr    }
1848817535bSAndreas Gohr
185c4584168SAndreas Gohr    /**
186c4584168SAndreas Gohr     * Recreate chunks and embeddings for all pages
187c4584168SAndreas Gohr     *
188c4584168SAndreas Gohr     * @return void
189ad38c5fdSAndreas Gohr     * @todo make skip regex configurable
190c4584168SAndreas Gohr     */
191*5284515dSAndreas Gohr    protected function createEmbeddings($clear)
1928817535bSAndreas Gohr    {
193ad38c5fdSAndreas Gohr        ini_set('memory_limit', -1); // we may need a lot of memory here
194*5284515dSAndreas Gohr        $this->helper->getEmbeddings()->createNewIndex('/(^|:)(playground|sandbox)(:|$)/', $clear);
195ad38c5fdSAndreas Gohr        $this->notice('Peak memory used: {memory}', ['memory' => filesize_h(memory_get_peak_usage(true))]);
1968817535bSAndreas Gohr    }
1978817535bSAndreas Gohr
198c4584168SAndreas Gohr    /**
199c4584168SAndreas Gohr     * Interactively ask for a value from the user
200c4584168SAndreas Gohr     *
201c4584168SAndreas Gohr     * @param string $prompt
202c4584168SAndreas Gohr     * @return string
203c4584168SAndreas Gohr     */
204c4584168SAndreas Gohr    protected function readLine($prompt)
205c4584168SAndreas Gohr    {
206c4584168SAndreas Gohr        $value = '';
2078817535bSAndreas Gohr
208c4584168SAndreas Gohr        while ($value === '') {
209c4584168SAndreas Gohr            echo $prompt;
210c4584168SAndreas Gohr            echo ': ';
211c4584168SAndreas Gohr
212c4584168SAndreas Gohr            $fh = fopen('php://stdin', 'r');
213c4584168SAndreas Gohr            $value = trim(fgets($fh));
214c4584168SAndreas Gohr            fclose($fh);
215c4584168SAndreas Gohr        }
216c4584168SAndreas Gohr
217c4584168SAndreas Gohr        return $value;
218c4584168SAndreas Gohr    }
2198817535bSAndreas Gohr}
2208817535bSAndreas Gohr
221