xref: /plugin/aichat/Embeddings.php (revision 8c08cb3f6b0f30c35f378fd151abfb219b75b92e)
18817535bSAndreas Gohr<?php
28817535bSAndreas Gohr
38817535bSAndreas Gohrnamespace dokuwiki\plugin\aichat;
48817535bSAndreas Gohr
5ab1f8ddeSAndreas Gohruse dokuwiki\Extension\Event;
67ebc7895Ssplitbrainuse dokuwiki\Extension\PluginInterface;
7294a9eafSAndreas Gohruse dokuwiki\plugin\aichat\Model\ChatInterface;
8294a9eafSAndreas Gohruse dokuwiki\plugin\aichat\Model\EmbeddingInterface;
9f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\AbstractStorage;
108817535bSAndreas Gohruse dokuwiki\Search\Indexer;
112ecc089aSAndreas Gohruse splitbrain\phpcli\CLI;
128817535bSAndreas Gohruse TikToken\Encoder;
138817535bSAndreas Gohruse Vanderlee\Sentence\Sentence;
148817535bSAndreas Gohr
159da5f0dfSAndreas Gohr/**
169da5f0dfSAndreas Gohr * Manage the embeddings index
179da5f0dfSAndreas Gohr *
189da5f0dfSAndreas Gohr * Pages are split into chunks of 1000 tokens each. For each chunk the embedding vector is fetched from
197ee8b02dSAndreas Gohr * OpenAI and stored in the Storage backend.
209da5f0dfSAndreas Gohr */
218817535bSAndreas Gohrclass Embeddings
228817535bSAndreas Gohr{
2368908844SAndreas Gohr    /** @var int maximum overlap between chunks in tokens */
2430b9cbc7Ssplitbrain    final public const MAX_OVERLAP_LEN = 200;
258817535bSAndreas Gohr
26294a9eafSAndreas Gohr    /** @var ChatInterface */
276a18e0f4SAndreas Gohr    protected $chatModel;
286a18e0f4SAndreas Gohr
29294a9eafSAndreas Gohr    /** @var EmbeddingInterface */
306a18e0f4SAndreas Gohr    protected $embedModel;
316a18e0f4SAndreas Gohr
322ecc089aSAndreas Gohr    /** @var CLI|null */
332ecc089aSAndreas Gohr    protected $logger;
3468908844SAndreas Gohr    /** @var Encoder */
3568908844SAndreas Gohr    protected $tokenEncoder;
368817535bSAndreas Gohr
377ee8b02dSAndreas Gohr    /** @var AbstractStorage */
387ee8b02dSAndreas Gohr    protected $storage;
397ee8b02dSAndreas Gohr
4068908844SAndreas Gohr    /** @var array remember sentences when chunking */
4168908844SAndreas Gohr    private $sentenceQueue = [];
4268908844SAndreas Gohr
43c2b7a1f7SAndreas Gohr    /** @var int the time spent for the last similar chunk retrieval */
44c2b7a1f7SAndreas Gohr    public $timeSpent = 0;
45c2b7a1f7SAndreas Gohr
4634a1c478SAndreas Gohr    protected $configChunkSize;
4734a1c478SAndreas Gohr    protected $configContextChunks;
48720bb43fSAndreas Gohr    protected $similarityThreshold;
4934a1c478SAndreas Gohr
5034a1c478SAndreas Gohr    /**
5134a1c478SAndreas Gohr     * Embeddings constructor.
5234a1c478SAndreas Gohr     *
5334a1c478SAndreas Gohr     * @param ChatInterface $chatModel
5434a1c478SAndreas Gohr     * @param EmbeddingInterface $embedModel
5534a1c478SAndreas Gohr     * @param AbstractStorage $storage
5634a1c478SAndreas Gohr     * @param array $config The plugin configuration
5734a1c478SAndreas Gohr     */
586a18e0f4SAndreas Gohr    public function __construct(
59294a9eafSAndreas Gohr        ChatInterface $chatModel,
60294a9eafSAndreas Gohr        EmbeddingInterface $embedModel,
6134a1c478SAndreas Gohr        AbstractStorage $storage,
6234a1c478SAndreas Gohr        $config
63*8c08cb3fSAndreas Gohr    ) {
646a18e0f4SAndreas Gohr        $this->chatModel = $chatModel;
656a18e0f4SAndreas Gohr        $this->embedModel = $embedModel;
66f6ef2e50SAndreas Gohr        $this->storage = $storage;
6734a1c478SAndreas Gohr        $this->configChunkSize = $config['chunkSize'];
6834a1c478SAndreas Gohr        $this->configContextChunks = $config['contextChunks'];
69720bb43fSAndreas Gohr        $this->similarityThreshold = $config['similarityThreshold'] / 100;
707ee8b02dSAndreas Gohr    }
717ee8b02dSAndreas Gohr
727ee8b02dSAndreas Gohr    /**
737ee8b02dSAndreas Gohr     * Access storage
747ee8b02dSAndreas Gohr     *
757ee8b02dSAndreas Gohr     * @return AbstractStorage
767ee8b02dSAndreas Gohr     */
777ee8b02dSAndreas Gohr    public function getStorage()
787ee8b02dSAndreas Gohr    {
797ee8b02dSAndreas Gohr        return $this->storage;
802ecc089aSAndreas Gohr    }
812ecc089aSAndreas Gohr
822ecc089aSAndreas Gohr    /**
832ecc089aSAndreas Gohr     * Add a logger instance
842ecc089aSAndreas Gohr     *
852ecc089aSAndreas Gohr     * @return void
862ecc089aSAndreas Gohr     */
872ecc089aSAndreas Gohr    public function setLogger(CLI $logger)
882ecc089aSAndreas Gohr    {
898817535bSAndreas Gohr        $this->logger = $logger;
908817535bSAndreas Gohr    }
918817535bSAndreas Gohr
922ecc089aSAndreas Gohr    /**
9368908844SAndreas Gohr     * Get the token encoder instance
9468908844SAndreas Gohr     *
9568908844SAndreas Gohr     * @return Encoder
9668908844SAndreas Gohr     */
9768908844SAndreas Gohr    public function getTokenEncoder()
9868908844SAndreas Gohr    {
997ebc7895Ssplitbrain        if (!$this->tokenEncoder instanceof Encoder) {
10068908844SAndreas Gohr            $this->tokenEncoder = new Encoder();
10168908844SAndreas Gohr        }
10268908844SAndreas Gohr        return $this->tokenEncoder;
10368908844SAndreas Gohr    }
10468908844SAndreas Gohr
10568908844SAndreas Gohr    /**
1066a18e0f4SAndreas Gohr     * Return the chunk size to use
1076a18e0f4SAndreas Gohr     *
1086a18e0f4SAndreas Gohr     * @return int
1096a18e0f4SAndreas Gohr     */
1106a18e0f4SAndreas Gohr    public function getChunkSize()
1116a18e0f4SAndreas Gohr    {
1126a18e0f4SAndreas Gohr        return min(
11334a1c478SAndreas Gohr            floor($this->chatModel->getMaxInputTokenLength() / 4), // be able to fit 4 chunks into the max input
11434a1c478SAndreas Gohr            floor($this->embedModel->getMaxInputTokenLength() * 0.9), // only use 90% of the embedding model to be safe
11534a1c478SAndreas Gohr            $this->configChunkSize, // this is usually the smallest
1166a18e0f4SAndreas Gohr        );
1176a18e0f4SAndreas Gohr    }
1186a18e0f4SAndreas Gohr
1196a18e0f4SAndreas Gohr    /**
1205284515dSAndreas Gohr     * Update the embeddings storage
1212ecc089aSAndreas Gohr     *
122ad38c5fdSAndreas Gohr     * @param string $skipRE Regular expression to filter out pages (full RE with delimiters)
123d5c102b3SAndreas Gohr     * @param string $matchRE Regular expression pages have to match to be included (full RE with delimiters)
1245284515dSAndreas Gohr     * @param bool $clear Should any existing storage be cleared before updating?
1252ecc089aSAndreas Gohr     * @return void
1265284515dSAndreas Gohr     * @throws \Exception
1272ecc089aSAndreas Gohr     */
128d5c102b3SAndreas Gohr    public function createNewIndex($skipRE = '', $matchRE = '', $clear = false)
1298817535bSAndreas Gohr    {
1308817535bSAndreas Gohr        $indexer = new Indexer();
1318817535bSAndreas Gohr        $pages = $indexer->getPages();
1328817535bSAndreas Gohr
133f6ef2e50SAndreas Gohr        $this->storage->startCreation($clear);
1345aa45b4dSAndreas Gohr        foreach ($pages as $pid => $page) {
1355aa45b4dSAndreas Gohr            $chunkID = $pid * 100; // chunk IDs start at page ID * 100
1365aa45b4dSAndreas Gohr
1375284515dSAndreas Gohr            if (
1385284515dSAndreas Gohr                !page_exists($page) ||
1395284515dSAndreas Gohr                isHiddenPage($page) ||
1404e206c13SAndreas Gohr                filesize(wikiFN($page)) < 150 || // skip very small pages
141d5c102b3SAndreas Gohr                ($skipRE && preg_match($skipRE, (string)$page)) ||
142d5c102b3SAndreas Gohr                ($matchRE && !preg_match($matchRE, ":$page"))
1435284515dSAndreas Gohr            ) {
1445284515dSAndreas Gohr                // this page should not be in the index (anymore)
1455284515dSAndreas Gohr                $this->storage->deletePageChunks($page, $chunkID);
1465284515dSAndreas Gohr                continue;
1475284515dSAndreas Gohr            }
1485284515dSAndreas Gohr
1497ee8b02dSAndreas Gohr            $firstChunk = $this->storage->getChunk($chunkID);
1507ee8b02dSAndreas Gohr            if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) {
1515aa45b4dSAndreas Gohr                // page is older than the chunks we have, reuse the existing chunks
1527ee8b02dSAndreas Gohr                $this->storage->reusePageChunks($page, $chunkID);
1537ebc7895Ssplitbrain                if ($this->logger instanceof CLI) $this->logger->info("Reusing chunks for $page");
1545aa45b4dSAndreas Gohr            } else {
1555aa45b4dSAndreas Gohr                // page is newer than the chunks we have, create new chunks
1567ee8b02dSAndreas Gohr                $this->storage->deletePageChunks($page, $chunkID);
157ecb0a423SAndreas Gohr                $chunks = $this->createPageChunks($page, $chunkID);
158ecb0a423SAndreas Gohr                if ($chunks) $this->storage->addPageChunks($chunks);
1595aa45b4dSAndreas Gohr            }
1605aa45b4dSAndreas Gohr        }
1617ee8b02dSAndreas Gohr        $this->storage->finalizeCreation();
1625aa45b4dSAndreas Gohr    }
1635aa45b4dSAndreas Gohr
1645aa45b4dSAndreas Gohr    /**
1657ee8b02dSAndreas Gohr     * Split the given page, fetch embedding vectors and return Chunks
1665aa45b4dSAndreas Gohr     *
16788305719SAndreas Gohr     * Will use the text renderer plugin if available to get the rendered text.
16888305719SAndreas Gohr     * Otherwise the raw wiki text is used.
16988305719SAndreas Gohr     *
1705aa45b4dSAndreas Gohr     * @param string $page Name of the page to split
1717ee8b02dSAndreas Gohr     * @param int $firstChunkID The ID of the first chunk of this page
1727ee8b02dSAndreas Gohr     * @return Chunk[] A list of chunks created for this page
173ab1f8ddeSAndreas Gohr     * @emits INDEXER_PAGE_ADD support plugins that add additional data to the page
1745aa45b4dSAndreas Gohr     * @throws \Exception
1755aa45b4dSAndreas Gohr     */
176ab1f8ddeSAndreas Gohr    public function createPageChunks($page, $firstChunkID)
1775aa45b4dSAndreas Gohr    {
1787ee8b02dSAndreas Gohr        $chunkList = [];
17988305719SAndreas Gohr
18088305719SAndreas Gohr        $textRenderer = plugin_load('renderer', 'text');
1817ebc7895Ssplitbrain        if ($textRenderer instanceof PluginInterface) {
18288305719SAndreas Gohr            global $ID;
18388305719SAndreas Gohr            $ID = $page;
18488305719SAndreas Gohr            $text = p_cached_output(wikiFN($page), 'text', $page);
18588305719SAndreas Gohr        } else {
18688305719SAndreas Gohr            $text = rawWiki($page);
18788305719SAndreas Gohr        }
18888305719SAndreas Gohr
189ab1f8ddeSAndreas Gohr        // allow plugins to modify the text before splitting
190ab1f8ddeSAndreas Gohr        $eventData = [
191ab1f8ddeSAndreas Gohr            'page' => $page,
192ab1f8ddeSAndreas Gohr            'body' => '',
193ab1f8ddeSAndreas Gohr            'metadata' => ['title' => $page, 'relation_references' => []],
194ab1f8ddeSAndreas Gohr        ];
195ab1f8ddeSAndreas Gohr        $event = new Event('INDEXER_PAGE_ADD', $eventData);
196ab1f8ddeSAndreas Gohr        if ($event->advise_before()) {
197ab1f8ddeSAndreas Gohr            $text = $eventData['body'] . ' ' . $text;
198ab1f8ddeSAndreas Gohr        } else {
199ab1f8ddeSAndreas Gohr            $text = $eventData['body'];
200ab1f8ddeSAndreas Gohr        }
201ab1f8ddeSAndreas Gohr
20288305719SAndreas Gohr        $parts = $this->splitIntoChunks($text);
2037ee8b02dSAndreas Gohr        foreach ($parts as $part) {
20430b9cbc7Ssplitbrain            if (trim((string)$part) == '') continue; // skip empty chunks
20593c1dbf4SAndreas Gohr
206ad38c5fdSAndreas Gohr            try {
2076a18e0f4SAndreas Gohr                $embedding = $this->embedModel->getEmbedding($part);
208ad38c5fdSAndreas Gohr            } catch (\Exception $e) {
2097ebc7895Ssplitbrain                if ($this->logger instanceof CLI) {
210ad38c5fdSAndreas Gohr                    $this->logger->error(
211ad38c5fdSAndreas Gohr                        'Failed to get embedding for chunk of page {page}: {msg}',
212ad38c5fdSAndreas Gohr                        ['page' => $page, 'msg' => $e->getMessage()]
213ad38c5fdSAndreas Gohr                    );
214ad38c5fdSAndreas Gohr                }
215ad38c5fdSAndreas Gohr                continue;
216ad38c5fdSAndreas Gohr            }
2177ee8b02dSAndreas Gohr            $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding);
2187ee8b02dSAndreas Gohr            $firstChunkID++;
2198817535bSAndreas Gohr        }
2207ebc7895Ssplitbrain        if ($this->logger instanceof CLI) {
2217ebc7895Ssplitbrain            if ($chunkList !== []) {
222f8d5ae01SAndreas Gohr                $this->logger->success(
223f8d5ae01SAndreas Gohr                    '{id} split into {count} chunks',
224f8d5ae01SAndreas Gohr                    ['id' => $page, 'count' => count($chunkList)]
225f8d5ae01SAndreas Gohr                );
22693c1dbf4SAndreas Gohr            } else {
22793c1dbf4SAndreas Gohr                $this->logger->warning('{id} could not be split into chunks', ['id' => $page]);
22893c1dbf4SAndreas Gohr            }
2298817535bSAndreas Gohr        }
2307ee8b02dSAndreas Gohr        return $chunkList;
2318817535bSAndreas Gohr    }
2328817535bSAndreas Gohr
2339e81bea7SAndreas Gohr    /**
2349e81bea7SAndreas Gohr     * Do a nearest neighbor search for chunks similar to the given question
2359e81bea7SAndreas Gohr     *
2369e81bea7SAndreas Gohr     * Returns only chunks the current user is allowed to read, may return an empty result.
23768908844SAndreas Gohr     * The number of returned chunks depends on the MAX_CONTEXT_LEN setting.
2389e81bea7SAndreas Gohr     *
2399e81bea7SAndreas Gohr     * @param string $query The question
240e33a1d7aSAndreas Gohr     * @param string $lang Limit results to this language
2417ee8b02dSAndreas Gohr     * @return Chunk[]
2429e81bea7SAndreas Gohr     * @throws \Exception
2439e81bea7SAndreas Gohr     */
244e33a1d7aSAndreas Gohr    public function getSimilarChunks($query, $lang = '')
2458817535bSAndreas Gohr    {
2469e81bea7SAndreas Gohr        global $auth;
2476a18e0f4SAndreas Gohr        $vector = $this->embedModel->getEmbedding($query);
2488817535bSAndreas Gohr
249e3640be8SAndreas Gohr        $fetch = min(
25034a1c478SAndreas Gohr            ($this->chatModel->getMaxInputTokenLength() / $this->getChunkSize()),
25134a1c478SAndreas Gohr            $this->configContextChunks
252f6ef2e50SAndreas Gohr        );
253aee9b383SAndreas Gohr
254aee9b383SAndreas Gohr        $time = microtime(true);
255e33a1d7aSAndreas Gohr        $chunks = $this->storage->getSimilarChunks($vector, $lang, $fetch);
2565f71c9bbSAndreas Gohr        $this->timeSpent = round(microtime(true) - $time, 2);
2577ebc7895Ssplitbrain        if ($this->logger instanceof CLI) {
258aee9b383SAndreas Gohr            $this->logger->info(
259aee9b383SAndreas Gohr                'Fetched {count} similar chunks from store in {time} seconds',
2605f71c9bbSAndreas Gohr                ['count' => count($chunks), 'time' => $this->timeSpent]
261aee9b383SAndreas Gohr            );
262aee9b383SAndreas Gohr        }
26368908844SAndreas Gohr
26468908844SAndreas Gohr        $size = 0;
2658817535bSAndreas Gohr        $result = [];
2667ee8b02dSAndreas Gohr        foreach ($chunks as $chunk) {
2679e81bea7SAndreas Gohr            // filter out chunks the user is not allowed to read
2687ee8b02dSAndreas Gohr            if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue;
269720bb43fSAndreas Gohr            if ($chunk->getScore() < $this->similarityThreshold) continue;
27068908844SAndreas Gohr
27168908844SAndreas Gohr            $chunkSize = count($this->getTokenEncoder()->encode($chunk->getText()));
27234a1c478SAndreas Gohr            if ($size + $chunkSize > $this->chatModel->getMaxInputTokenLength()) break; // we have enough
27368908844SAndreas Gohr
2749e81bea7SAndreas Gohr            $result[] = $chunk;
27568908844SAndreas Gohr            $size += $chunkSize;
2768817535bSAndreas Gohr        }
2778817535bSAndreas Gohr        return $result;
2788817535bSAndreas Gohr    }
2798817535bSAndreas Gohr
2805786be46SAndreas Gohr
2815786be46SAndreas Gohr    /**
2828817535bSAndreas Gohr     * @param $text
2838817535bSAndreas Gohr     * @return array
2848817535bSAndreas Gohr     * @throws \Exception
2858817535bSAndreas Gohr     * @todo support splitting too long sentences
2868817535bSAndreas Gohr     */
287ab1f8ddeSAndreas Gohr    protected function splitIntoChunks($text)
2888817535bSAndreas Gohr    {
2898817535bSAndreas Gohr        $sentenceSplitter = new Sentence();
29068908844SAndreas Gohr        $tiktok = $this->getTokenEncoder();
2918817535bSAndreas Gohr
2928817535bSAndreas Gohr        $chunks = [];
2938817535bSAndreas Gohr        $sentences = $sentenceSplitter->split($text);
2948817535bSAndreas Gohr
2958817535bSAndreas Gohr        $chunklen = 0;
2968817535bSAndreas Gohr        $chunk = '';
2978817535bSAndreas Gohr        while ($sentence = array_shift($sentences)) {
2988817535bSAndreas Gohr            $slen = count($tiktok->encode($sentence));
2996a18e0f4SAndreas Gohr            if ($slen > $this->getChunkSize()) {
3008817535bSAndreas Gohr                // sentence is too long, we need to split it further
301f8d5ae01SAndreas Gohr                if ($this->logger instanceof CLI) $this->logger->warning(
302f8d5ae01SAndreas Gohr                    'Sentence too long, splitting not implemented yet'
303f8d5ae01SAndreas Gohr                );
304ad38c5fdSAndreas Gohr                continue;
3058817535bSAndreas Gohr            }
3068817535bSAndreas Gohr
3076a18e0f4SAndreas Gohr            if ($chunklen + $slen < $this->getChunkSize()) {
3088817535bSAndreas Gohr                // add to current chunk
3098817535bSAndreas Gohr                $chunk .= $sentence;
3108817535bSAndreas Gohr                $chunklen += $slen;
31168908844SAndreas Gohr                // remember sentence for overlap check
31268908844SAndreas Gohr                $this->rememberSentence($sentence);
3138817535bSAndreas Gohr            } else {
31468908844SAndreas Gohr                // add current chunk to result
315ab1f8ddeSAndreas Gohr                $chunk = trim($chunk);
316ab1f8ddeSAndreas Gohr                if ($chunk !== '') $chunks[] = $chunk;
31768908844SAndreas Gohr
31868908844SAndreas Gohr                // start new chunk with remembered sentences
3197ebc7895Ssplitbrain                $chunk = implode(' ', $this->sentenceQueue);
32068908844SAndreas Gohr                $chunk .= $sentence;
32168908844SAndreas Gohr                $chunklen = count($tiktok->encode($chunk));
3228817535bSAndreas Gohr            }
3238817535bSAndreas Gohr        }
3248817535bSAndreas Gohr        $chunks[] = $chunk;
3258817535bSAndreas Gohr
3268817535bSAndreas Gohr        return $chunks;
3278817535bSAndreas Gohr    }
32868908844SAndreas Gohr
32968908844SAndreas Gohr    /**
33068908844SAndreas Gohr     * Add a sentence to the queue of remembered sentences
33168908844SAndreas Gohr     *
33268908844SAndreas Gohr     * @param string $sentence
33368908844SAndreas Gohr     * @return void
33468908844SAndreas Gohr     */
33568908844SAndreas Gohr    protected function rememberSentence($sentence)
33668908844SAndreas Gohr    {
33768908844SAndreas Gohr        // add sentence to queue
33868908844SAndreas Gohr        $this->sentenceQueue[] = $sentence;
33968908844SAndreas Gohr
34068908844SAndreas Gohr        // remove oldest sentences from queue until we are below the max overlap
34168908844SAndreas Gohr        $encoder = $this->getTokenEncoder();
3427ebc7895Ssplitbrain        while (count($encoder->encode(implode(' ', $this->sentenceQueue))) > self::MAX_OVERLAP_LEN) {
34368908844SAndreas Gohr            array_shift($this->sentenceQueue);
34468908844SAndreas Gohr        }
34568908844SAndreas Gohr    }
3468817535bSAndreas Gohr}
347