xref: /plugin/aichat/Embeddings.php (revision e33a1d7adcbf36c57f516e2f829ec8ad59cdb47b)
18817535bSAndreas Gohr<?php
28817535bSAndreas Gohr
38817535bSAndreas Gohrnamespace dokuwiki\plugin\aichat;
48817535bSAndreas Gohr
5f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Model\AbstractModel;
6f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\AbstractStorage;
78817535bSAndreas Gohruse dokuwiki\Search\Indexer;
82ecc089aSAndreas Gohruse splitbrain\phpcli\CLI;
98817535bSAndreas Gohruse TikToken\Encoder;
108817535bSAndreas Gohruse Vanderlee\Sentence\Sentence;
118817535bSAndreas Gohr
129da5f0dfSAndreas Gohr/**
139da5f0dfSAndreas Gohr * Manage the embeddings index
149da5f0dfSAndreas Gohr *
159da5f0dfSAndreas Gohr * Pages are split into chunks of 1000 tokens each. For each chunk the embedding vector is fetched from
167ee8b02dSAndreas Gohr * OpenAI and stored in the Storage backend.
179da5f0dfSAndreas Gohr */
188817535bSAndreas Gohrclass Embeddings
198817535bSAndreas Gohr{
2068908844SAndreas Gohr    /** @var int maximum overlap between chunks in tokens */
2168908844SAndreas Gohr    const MAX_OVERLAP_LEN = 200;
228817535bSAndreas Gohr
23f6ef2e50SAndreas Gohr    /** @var AbstractModel */
24f6ef2e50SAndreas Gohr    protected $model;
252ecc089aSAndreas Gohr    /** @var CLI|null */
262ecc089aSAndreas Gohr    protected $logger;
2768908844SAndreas Gohr    /** @var Encoder */
2868908844SAndreas Gohr    protected $tokenEncoder;
298817535bSAndreas Gohr
307ee8b02dSAndreas Gohr    /** @var AbstractStorage */
317ee8b02dSAndreas Gohr    protected $storage;
327ee8b02dSAndreas Gohr
3368908844SAndreas Gohr    /** @var array remember sentences when chunking */
3468908844SAndreas Gohr    private $sentenceQueue = [];
3568908844SAndreas Gohr
362ecc089aSAndreas Gohr    /**
37f6ef2e50SAndreas Gohr     * @param AbstractModel $model
382ecc089aSAndreas Gohr     */
39f6ef2e50SAndreas Gohr    public function __construct(AbstractModel $model, AbstractStorage $storage)
408817535bSAndreas Gohr    {
41f6ef2e50SAndreas Gohr        $this->model = $model;
42f6ef2e50SAndreas Gohr        $this->storage = $storage;
437ee8b02dSAndreas Gohr    }
447ee8b02dSAndreas Gohr
457ee8b02dSAndreas Gohr    /**
467ee8b02dSAndreas Gohr     * Access storage
477ee8b02dSAndreas Gohr     *
487ee8b02dSAndreas Gohr     * @return AbstractStorage
497ee8b02dSAndreas Gohr     */
507ee8b02dSAndreas Gohr    public function getStorage()
517ee8b02dSAndreas Gohr    {
527ee8b02dSAndreas Gohr        return $this->storage;
532ecc089aSAndreas Gohr    }
542ecc089aSAndreas Gohr
552ecc089aSAndreas Gohr    /**
562ecc089aSAndreas Gohr     * Add a logger instance
572ecc089aSAndreas Gohr     *
582ecc089aSAndreas Gohr     * @param CLI $logger
592ecc089aSAndreas Gohr     * @return void
602ecc089aSAndreas Gohr     */
612ecc089aSAndreas Gohr    public function setLogger(CLI $logger)
622ecc089aSAndreas Gohr    {
638817535bSAndreas Gohr        $this->logger = $logger;
648817535bSAndreas Gohr    }
658817535bSAndreas Gohr
662ecc089aSAndreas Gohr    /**
6768908844SAndreas Gohr     * Get the token encoder instance
6868908844SAndreas Gohr     *
6968908844SAndreas Gohr     * @return Encoder
7068908844SAndreas Gohr     */
7168908844SAndreas Gohr    public function getTokenEncoder()
7268908844SAndreas Gohr    {
7368908844SAndreas Gohr        if ($this->tokenEncoder === null) {
7468908844SAndreas Gohr            $this->tokenEncoder = new Encoder();
7568908844SAndreas Gohr        }
7668908844SAndreas Gohr        return $this->tokenEncoder;
7768908844SAndreas Gohr    }
7868908844SAndreas Gohr
7968908844SAndreas Gohr    /**
805284515dSAndreas Gohr     * Update the embeddings storage
812ecc089aSAndreas Gohr     *
82ad38c5fdSAndreas Gohr     * @param string $skipRE Regular expression to filter out pages (full RE with delimiters)
835284515dSAndreas Gohr     * @param bool $clear Should any existing storage be cleared before updating?
842ecc089aSAndreas Gohr     * @return void
855284515dSAndreas Gohr     * @throws \Exception
862ecc089aSAndreas Gohr     */
875284515dSAndreas Gohr    public function createNewIndex($skipRE = '', $clear = false)
888817535bSAndreas Gohr    {
898817535bSAndreas Gohr        $indexer = new Indexer();
908817535bSAndreas Gohr        $pages = $indexer->getPages();
918817535bSAndreas Gohr
92f6ef2e50SAndreas Gohr        $this->storage->startCreation($clear);
935aa45b4dSAndreas Gohr        foreach ($pages as $pid => $page) {
945aa45b4dSAndreas Gohr            $chunkID = $pid * 100; // chunk IDs start at page ID * 100
955aa45b4dSAndreas Gohr
965284515dSAndreas Gohr            if (
975284515dSAndreas Gohr                !page_exists($page) ||
985284515dSAndreas Gohr                isHiddenPage($page) ||
994e206c13SAndreas Gohr                filesize(wikiFN($page)) < 150 || // skip very small pages
1005284515dSAndreas Gohr                ($skipRE && preg_match($skipRE, $page))
1015284515dSAndreas Gohr            ) {
1025284515dSAndreas Gohr                // this page should not be in the index (anymore)
1035284515dSAndreas Gohr                $this->storage->deletePageChunks($page, $chunkID);
1045284515dSAndreas Gohr                continue;
1055284515dSAndreas Gohr            }
1065284515dSAndreas Gohr
1077ee8b02dSAndreas Gohr            $firstChunk = $this->storage->getChunk($chunkID);
1087ee8b02dSAndreas Gohr            if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) {
1095aa45b4dSAndreas Gohr                // page is older than the chunks we have, reuse the existing chunks
1107ee8b02dSAndreas Gohr                $this->storage->reusePageChunks($page, $chunkID);
11133128f96SAndreas Gohr                if ($this->logger) $this->logger->info("Reusing chunks for $page");
1125aa45b4dSAndreas Gohr            } else {
1135aa45b4dSAndreas Gohr                // page is newer than the chunks we have, create new chunks
1147ee8b02dSAndreas Gohr                $this->storage->deletePageChunks($page, $chunkID);
1157ee8b02dSAndreas Gohr                $this->storage->addPageChunks($this->createPageChunks($page, $chunkID));
1165aa45b4dSAndreas Gohr            }
1175aa45b4dSAndreas Gohr        }
1187ee8b02dSAndreas Gohr        $this->storage->finalizeCreation();
1195aa45b4dSAndreas Gohr    }
1205aa45b4dSAndreas Gohr
1215aa45b4dSAndreas Gohr    /**
1227ee8b02dSAndreas Gohr     * Split the given page, fetch embedding vectors and return Chunks
1235aa45b4dSAndreas Gohr     *
12488305719SAndreas Gohr     * Will use the text renderer plugin if available to get the rendered text.
12588305719SAndreas Gohr     * Otherwise the raw wiki text is used.
12688305719SAndreas Gohr     *
1275aa45b4dSAndreas Gohr     * @param string $page Name of the page to split
1287ee8b02dSAndreas Gohr     * @param int $firstChunkID The ID of the first chunk of this page
1297ee8b02dSAndreas Gohr     * @return Chunk[] A list of chunks created for this page
1305aa45b4dSAndreas Gohr     * @throws \Exception
1315aa45b4dSAndreas Gohr     */
1327ee8b02dSAndreas Gohr    protected function createPageChunks($page, $firstChunkID)
1335aa45b4dSAndreas Gohr    {
1347ee8b02dSAndreas Gohr        $chunkList = [];
13588305719SAndreas Gohr
13688305719SAndreas Gohr        $textRenderer = plugin_load('renderer', 'text');
13788305719SAndreas Gohr        if ($textRenderer) {
13888305719SAndreas Gohr            global $ID;
13988305719SAndreas Gohr            $ID = $page;
14088305719SAndreas Gohr            $text = p_cached_output(wikiFN($page), 'text', $page);
14188305719SAndreas Gohr        } else {
14288305719SAndreas Gohr            $text = rawWiki($page);
14388305719SAndreas Gohr        }
14488305719SAndreas Gohr
14588305719SAndreas Gohr        $parts = $this->splitIntoChunks($text);
1467ee8b02dSAndreas Gohr        foreach ($parts as $part) {
14793c1dbf4SAndreas Gohr            if (trim($part) == '') continue; // skip empty chunks
14893c1dbf4SAndreas Gohr
149ad38c5fdSAndreas Gohr            try {
150f6ef2e50SAndreas Gohr                $embedding = $this->model->getEmbedding($part);
151ad38c5fdSAndreas Gohr            } catch (\Exception $e) {
152ad38c5fdSAndreas Gohr                if ($this->logger) {
153ad38c5fdSAndreas Gohr                    $this->logger->error(
154ad38c5fdSAndreas Gohr                        'Failed to get embedding for chunk of page {page}: {msg}',
155ad38c5fdSAndreas Gohr                        ['page' => $page, 'msg' => $e->getMessage()]
156ad38c5fdSAndreas Gohr                    );
157ad38c5fdSAndreas Gohr                }
158ad38c5fdSAndreas Gohr                continue;
159ad38c5fdSAndreas Gohr            }
1607ee8b02dSAndreas Gohr            $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding);
1617ee8b02dSAndreas Gohr            $firstChunkID++;
1628817535bSAndreas Gohr        }
1638817535bSAndreas Gohr        if ($this->logger) {
16493c1dbf4SAndreas Gohr            if (count($chunkList)) {
16593c1dbf4SAndreas Gohr                $this->logger->success('{id} split into {count} chunks', ['id' => $page, 'count' => count($chunkList)]);
16693c1dbf4SAndreas Gohr            } else {
16793c1dbf4SAndreas Gohr                $this->logger->warning('{id} could not be split into chunks', ['id' => $page]);
16893c1dbf4SAndreas Gohr            }
1698817535bSAndreas Gohr        }
1707ee8b02dSAndreas Gohr        return $chunkList;
1718817535bSAndreas Gohr    }
1728817535bSAndreas Gohr
1739e81bea7SAndreas Gohr    /**
1749e81bea7SAndreas Gohr     * Do a nearest neighbor search for chunks similar to the given question
1759e81bea7SAndreas Gohr     *
1769e81bea7SAndreas Gohr     * Returns only chunks the current user is allowed to read, may return an empty result.
17768908844SAndreas Gohr     * The number of returned chunks depends on the MAX_CONTEXT_LEN setting.
1789e81bea7SAndreas Gohr     *
1799e81bea7SAndreas Gohr     * @param string $query The question
180*e33a1d7aSAndreas Gohr     * @param string $lang Limit results to this language
1817ee8b02dSAndreas Gohr     * @return Chunk[]
1829e81bea7SAndreas Gohr     * @throws \Exception
1839e81bea7SAndreas Gohr     */
184*e33a1d7aSAndreas Gohr    public function getSimilarChunks($query, $lang='')
1858817535bSAndreas Gohr    {
1869e81bea7SAndreas Gohr        global $auth;
187f6ef2e50SAndreas Gohr        $vector = $this->model->getEmbedding($query);
1888817535bSAndreas Gohr
189f6ef2e50SAndreas Gohr        $fetch = ceil(
190f6ef2e50SAndreas Gohr            ($this->model->getMaxContextTokenLength() / $this->model->getMaxEmbeddingTokenLength())
191f6ef2e50SAndreas Gohr            * 1.5 // fetch a few more than needed, since not all chunks are maximum length
192f6ef2e50SAndreas Gohr        );
193aee9b383SAndreas Gohr
194aee9b383SAndreas Gohr        $time = microtime(true);
195*e33a1d7aSAndreas Gohr        $chunks = $this->storage->getSimilarChunks($vector, $lang, $fetch);
196aee9b383SAndreas Gohr        if ($this->logger) {
197aee9b383SAndreas Gohr            $this->logger->info(
198aee9b383SAndreas Gohr                'Fetched {count} similar chunks from store in {time} seconds',
199aee9b383SAndreas Gohr                ['count' => count($chunks), 'time' => round(microtime(true) - $time, 2)]
200aee9b383SAndreas Gohr            );
201aee9b383SAndreas Gohr        }
20268908844SAndreas Gohr
20368908844SAndreas Gohr        $size = 0;
2048817535bSAndreas Gohr        $result = [];
2057ee8b02dSAndreas Gohr        foreach ($chunks as $chunk) {
2069e81bea7SAndreas Gohr            // filter out chunks the user is not allowed to read
2077ee8b02dSAndreas Gohr            if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue;
20868908844SAndreas Gohr
20968908844SAndreas Gohr            $chunkSize = count($this->getTokenEncoder()->encode($chunk->getText()));
210f6ef2e50SAndreas Gohr            if ($size + $chunkSize > $this->model->getMaxContextTokenLength()) break; // we have enough
21168908844SAndreas Gohr
2129e81bea7SAndreas Gohr            $result[] = $chunk;
21368908844SAndreas Gohr            $size += $chunkSize;
2148817535bSAndreas Gohr        }
2158817535bSAndreas Gohr        return $result;
2168817535bSAndreas Gohr    }
2178817535bSAndreas Gohr
2185786be46SAndreas Gohr
2195786be46SAndreas Gohr    /**
2208817535bSAndreas Gohr     * @param $text
2218817535bSAndreas Gohr     * @return array
2228817535bSAndreas Gohr     * @throws \Exception
2238817535bSAndreas Gohr     * @todo support splitting too long sentences
2248817535bSAndreas Gohr     */
225ad38c5fdSAndreas Gohr    public function splitIntoChunks($text)
2268817535bSAndreas Gohr    {
2278817535bSAndreas Gohr        $sentenceSplitter = new Sentence();
22868908844SAndreas Gohr        $tiktok = $this->getTokenEncoder();
2298817535bSAndreas Gohr
2308817535bSAndreas Gohr        $chunks = [];
2318817535bSAndreas Gohr        $sentences = $sentenceSplitter->split($text);
2328817535bSAndreas Gohr
2338817535bSAndreas Gohr        $chunklen = 0;
2348817535bSAndreas Gohr        $chunk = '';
2358817535bSAndreas Gohr        while ($sentence = array_shift($sentences)) {
2368817535bSAndreas Gohr            $slen = count($tiktok->encode($sentence));
237f6ef2e50SAndreas Gohr            if ($slen > $this->model->getMaxEmbeddingTokenLength()) {
2388817535bSAndreas Gohr                // sentence is too long, we need to split it further
239ad38c5fdSAndreas Gohr                if ($this->logger) $this->logger->warning('Sentence too long, splitting not implemented yet');
240ad38c5fdSAndreas Gohr                continue;
2418817535bSAndreas Gohr            }
2428817535bSAndreas Gohr
243f6ef2e50SAndreas Gohr            if ($chunklen + $slen < $this->model->getMaxEmbeddingTokenLength()) {
2448817535bSAndreas Gohr                // add to current chunk
2458817535bSAndreas Gohr                $chunk .= $sentence;
2468817535bSAndreas Gohr                $chunklen += $slen;
24768908844SAndreas Gohr                // remember sentence for overlap check
24868908844SAndreas Gohr                $this->rememberSentence($sentence);
2498817535bSAndreas Gohr            } else {
25068908844SAndreas Gohr                // add current chunk to result
2518817535bSAndreas Gohr                $chunks[] = $chunk;
25268908844SAndreas Gohr
25368908844SAndreas Gohr                // start new chunk with remembered sentences
25468908844SAndreas Gohr                $chunk = join(' ', $this->sentenceQueue);
25568908844SAndreas Gohr                $chunk .= $sentence;
25668908844SAndreas Gohr                $chunklen = count($tiktok->encode($chunk));
2578817535bSAndreas Gohr            }
2588817535bSAndreas Gohr        }
2598817535bSAndreas Gohr        $chunks[] = $chunk;
2608817535bSAndreas Gohr
2618817535bSAndreas Gohr        return $chunks;
2628817535bSAndreas Gohr    }
26368908844SAndreas Gohr
26468908844SAndreas Gohr    /**
26568908844SAndreas Gohr     * Add a sentence to the queue of remembered sentences
26668908844SAndreas Gohr     *
26768908844SAndreas Gohr     * @param string $sentence
26868908844SAndreas Gohr     * @return void
26968908844SAndreas Gohr     */
27068908844SAndreas Gohr    protected function rememberSentence($sentence)
27168908844SAndreas Gohr    {
27268908844SAndreas Gohr        // add sentence to queue
27368908844SAndreas Gohr        $this->sentenceQueue[] = $sentence;
27468908844SAndreas Gohr
27568908844SAndreas Gohr        // remove oldest sentences from queue until we are below the max overlap
27668908844SAndreas Gohr        $encoder = $this->getTokenEncoder();
27768908844SAndreas Gohr        while (count($encoder->encode(join(' ', $this->sentenceQueue))) > self::MAX_OVERLAP_LEN) {
27868908844SAndreas Gohr            array_shift($this->sentenceQueue);
27968908844SAndreas Gohr        }
28068908844SAndreas Gohr    }
2818817535bSAndreas Gohr}
282