xref: /plugin/aichat/Embeddings.php (revision 5f71c9bbe31dfcc1db5ab9659debc4833c4ec6eb)
18817535bSAndreas Gohr<?php
28817535bSAndreas Gohr
38817535bSAndreas Gohrnamespace dokuwiki\plugin\aichat;
48817535bSAndreas Gohr
57ebc7895Ssplitbrainuse dokuwiki\Extension\PluginInterface;
6294a9eafSAndreas Gohruse dokuwiki\plugin\aichat\Model\ChatInterface;
7294a9eafSAndreas Gohruse dokuwiki\plugin\aichat\Model\EmbeddingInterface;
8f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\AbstractStorage;
98817535bSAndreas Gohruse dokuwiki\Search\Indexer;
102ecc089aSAndreas Gohruse splitbrain\phpcli\CLI;
118817535bSAndreas Gohruse TikToken\Encoder;
128817535bSAndreas Gohruse Vanderlee\Sentence\Sentence;
138817535bSAndreas Gohr
149da5f0dfSAndreas Gohr/**
159da5f0dfSAndreas Gohr * Manage the embeddings index
169da5f0dfSAndreas Gohr *
179da5f0dfSAndreas Gohr * Pages are split into chunks of 1000 tokens each. For each chunk the embedding vector is fetched from
187ee8b02dSAndreas Gohr * OpenAI and stored in the Storage backend.
199da5f0dfSAndreas Gohr */
208817535bSAndreas Gohrclass Embeddings
218817535bSAndreas Gohr{
2268908844SAndreas Gohr    /** @var int maximum overlap between chunks in tokens */
2330b9cbc7Ssplitbrain    final public const MAX_OVERLAP_LEN = 200;
248817535bSAndreas Gohr
25294a9eafSAndreas Gohr    /** @var ChatInterface */
266a18e0f4SAndreas Gohr    protected $chatModel;
276a18e0f4SAndreas Gohr
28294a9eafSAndreas Gohr    /** @var EmbeddingInterface */
296a18e0f4SAndreas Gohr    protected $embedModel;
306a18e0f4SAndreas Gohr
312ecc089aSAndreas Gohr    /** @var CLI|null */
322ecc089aSAndreas Gohr    protected $logger;
3368908844SAndreas Gohr    /** @var Encoder */
3468908844SAndreas Gohr    protected $tokenEncoder;
358817535bSAndreas Gohr
367ee8b02dSAndreas Gohr    /** @var AbstractStorage */
377ee8b02dSAndreas Gohr    protected $storage;
387ee8b02dSAndreas Gohr
3968908844SAndreas Gohr    /** @var array remember sentences when chunking */
4068908844SAndreas Gohr    private $sentenceQueue = [];
4168908844SAndreas Gohr
42c2b7a1f7SAndreas Gohr    /** @var int the time spent for the last similar chunk retrieval */
43c2b7a1f7SAndreas Gohr    public $timeSpent = 0;
44c2b7a1f7SAndreas Gohr
4534a1c478SAndreas Gohr    protected $configChunkSize;
4634a1c478SAndreas Gohr    protected $configContextChunks;
4734a1c478SAndreas Gohr
4834a1c478SAndreas Gohr    /**
4934a1c478SAndreas Gohr     * Embeddings constructor.
5034a1c478SAndreas Gohr     *
5134a1c478SAndreas Gohr     * @param ChatInterface $chatModel
5234a1c478SAndreas Gohr     * @param EmbeddingInterface $embedModel
5334a1c478SAndreas Gohr     * @param AbstractStorage $storage
5434a1c478SAndreas Gohr     * @param array $config The plugin configuration
5534a1c478SAndreas Gohr     */
566a18e0f4SAndreas Gohr    public function __construct(
57294a9eafSAndreas Gohr        ChatInterface      $chatModel,
58294a9eafSAndreas Gohr        EmbeddingInterface $embedModel,
5934a1c478SAndreas Gohr        AbstractStorage    $storage,
6034a1c478SAndreas Gohr                           $config
6134a1c478SAndreas Gohr    )
6234a1c478SAndreas Gohr    {
636a18e0f4SAndreas Gohr        $this->chatModel = $chatModel;
646a18e0f4SAndreas Gohr        $this->embedModel = $embedModel;
65f6ef2e50SAndreas Gohr        $this->storage = $storage;
6634a1c478SAndreas Gohr        $this->configChunkSize = $config['chunkSize'];
6734a1c478SAndreas Gohr        $this->configContextChunks = $config['contextChunks'];
687ee8b02dSAndreas Gohr    }
697ee8b02dSAndreas Gohr
707ee8b02dSAndreas Gohr    /**
717ee8b02dSAndreas Gohr     * Access storage
727ee8b02dSAndreas Gohr     *
737ee8b02dSAndreas Gohr     * @return AbstractStorage
747ee8b02dSAndreas Gohr     */
757ee8b02dSAndreas Gohr    public function getStorage()
767ee8b02dSAndreas Gohr    {
777ee8b02dSAndreas Gohr        return $this->storage;
782ecc089aSAndreas Gohr    }
792ecc089aSAndreas Gohr
802ecc089aSAndreas Gohr    /**
812ecc089aSAndreas Gohr     * Add a logger instance
822ecc089aSAndreas Gohr     *
832ecc089aSAndreas Gohr     * @return void
842ecc089aSAndreas Gohr     */
852ecc089aSAndreas Gohr    public function setLogger(CLI $logger)
862ecc089aSAndreas Gohr    {
878817535bSAndreas Gohr        $this->logger = $logger;
888817535bSAndreas Gohr    }
898817535bSAndreas Gohr
902ecc089aSAndreas Gohr    /**
9168908844SAndreas Gohr     * Get the token encoder instance
9268908844SAndreas Gohr     *
9368908844SAndreas Gohr     * @return Encoder
9468908844SAndreas Gohr     */
9568908844SAndreas Gohr    public function getTokenEncoder()
9668908844SAndreas Gohr    {
977ebc7895Ssplitbrain        if (!$this->tokenEncoder instanceof Encoder) {
9868908844SAndreas Gohr            $this->tokenEncoder = new Encoder();
9968908844SAndreas Gohr        }
10068908844SAndreas Gohr        return $this->tokenEncoder;
10168908844SAndreas Gohr    }
10268908844SAndreas Gohr
10368908844SAndreas Gohr    /**
1046a18e0f4SAndreas Gohr     * Return the chunk size to use
1056a18e0f4SAndreas Gohr     *
1066a18e0f4SAndreas Gohr     * @return int
1076a18e0f4SAndreas Gohr     */
1086a18e0f4SAndreas Gohr    public function getChunkSize()
1096a18e0f4SAndreas Gohr    {
1106a18e0f4SAndreas Gohr        return min(
11134a1c478SAndreas Gohr            floor($this->chatModel->getMaxInputTokenLength() / 4), // be able to fit 4 chunks into the max input
11234a1c478SAndreas Gohr            floor($this->embedModel->getMaxInputTokenLength() * 0.9), // only use 90% of the embedding model to be safe
11334a1c478SAndreas Gohr            $this->configChunkSize, // this is usually the smallest
1146a18e0f4SAndreas Gohr        );
1156a18e0f4SAndreas Gohr    }
1166a18e0f4SAndreas Gohr
1176a18e0f4SAndreas Gohr    /**
1185284515dSAndreas Gohr     * Update the embeddings storage
1192ecc089aSAndreas Gohr     *
120ad38c5fdSAndreas Gohr     * @param string $skipRE Regular expression to filter out pages (full RE with delimiters)
121d5c102b3SAndreas Gohr     * @param string $matchRE Regular expression pages have to match to be included (full RE with delimiters)
1225284515dSAndreas Gohr     * @param bool $clear Should any existing storage be cleared before updating?
1232ecc089aSAndreas Gohr     * @return void
1245284515dSAndreas Gohr     * @throws \Exception
1252ecc089aSAndreas Gohr     */
126d5c102b3SAndreas Gohr    public function createNewIndex($skipRE = '', $matchRE = '', $clear = false)
1278817535bSAndreas Gohr    {
1288817535bSAndreas Gohr        $indexer = new Indexer();
1298817535bSAndreas Gohr        $pages = $indexer->getPages();
1308817535bSAndreas Gohr
131f6ef2e50SAndreas Gohr        $this->storage->startCreation($clear);
1325aa45b4dSAndreas Gohr        foreach ($pages as $pid => $page) {
1335aa45b4dSAndreas Gohr            $chunkID = $pid * 100; // chunk IDs start at page ID * 100
1345aa45b4dSAndreas Gohr
1355284515dSAndreas Gohr            if (
1365284515dSAndreas Gohr                !page_exists($page) ||
1375284515dSAndreas Gohr                isHiddenPage($page) ||
1384e206c13SAndreas Gohr                filesize(wikiFN($page)) < 150 || // skip very small pages
139d5c102b3SAndreas Gohr                ($skipRE && preg_match($skipRE, (string)$page)) ||
140d5c102b3SAndreas Gohr                ($matchRE && !preg_match($matchRE, ":$page"))
1415284515dSAndreas Gohr            ) {
1425284515dSAndreas Gohr                // this page should not be in the index (anymore)
1435284515dSAndreas Gohr                $this->storage->deletePageChunks($page, $chunkID);
1445284515dSAndreas Gohr                continue;
1455284515dSAndreas Gohr            }
1465284515dSAndreas Gohr
1477ee8b02dSAndreas Gohr            $firstChunk = $this->storage->getChunk($chunkID);
1487ee8b02dSAndreas Gohr            if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) {
1495aa45b4dSAndreas Gohr                // page is older than the chunks we have, reuse the existing chunks
1507ee8b02dSAndreas Gohr                $this->storage->reusePageChunks($page, $chunkID);
1517ebc7895Ssplitbrain                if ($this->logger instanceof CLI) $this->logger->info("Reusing chunks for $page");
1525aa45b4dSAndreas Gohr            } else {
1535aa45b4dSAndreas Gohr                // page is newer than the chunks we have, create new chunks
1547ee8b02dSAndreas Gohr                $this->storage->deletePageChunks($page, $chunkID);
155ecb0a423SAndreas Gohr                $chunks = $this->createPageChunks($page, $chunkID);
156ecb0a423SAndreas Gohr                if ($chunks) $this->storage->addPageChunks($chunks);
1575aa45b4dSAndreas Gohr            }
1585aa45b4dSAndreas Gohr        }
1597ee8b02dSAndreas Gohr        $this->storage->finalizeCreation();
1605aa45b4dSAndreas Gohr    }
1615aa45b4dSAndreas Gohr
1625aa45b4dSAndreas Gohr    /**
1637ee8b02dSAndreas Gohr     * Split the given page, fetch embedding vectors and return Chunks
1645aa45b4dSAndreas Gohr     *
16588305719SAndreas Gohr     * Will use the text renderer plugin if available to get the rendered text.
16688305719SAndreas Gohr     * Otherwise the raw wiki text is used.
16788305719SAndreas Gohr     *
1685aa45b4dSAndreas Gohr     * @param string $page Name of the page to split
1697ee8b02dSAndreas Gohr     * @param int $firstChunkID The ID of the first chunk of this page
1707ee8b02dSAndreas Gohr     * @return Chunk[] A list of chunks created for this page
1715aa45b4dSAndreas Gohr     * @throws \Exception
1725aa45b4dSAndreas Gohr     */
1737ee8b02dSAndreas Gohr    protected function createPageChunks($page, $firstChunkID)
1745aa45b4dSAndreas Gohr    {
1757ee8b02dSAndreas Gohr        $chunkList = [];
17688305719SAndreas Gohr
17788305719SAndreas Gohr        $textRenderer = plugin_load('renderer', 'text');
1787ebc7895Ssplitbrain        if ($textRenderer instanceof PluginInterface) {
17988305719SAndreas Gohr            global $ID;
18088305719SAndreas Gohr            $ID = $page;
18188305719SAndreas Gohr            $text = p_cached_output(wikiFN($page), 'text', $page);
18288305719SAndreas Gohr        } else {
18388305719SAndreas Gohr            $text = rawWiki($page);
18488305719SAndreas Gohr        }
18588305719SAndreas Gohr
18688305719SAndreas Gohr        $parts = $this->splitIntoChunks($text);
1877ee8b02dSAndreas Gohr        foreach ($parts as $part) {
18830b9cbc7Ssplitbrain            if (trim((string)$part) == '') continue; // skip empty chunks
18993c1dbf4SAndreas Gohr
190ad38c5fdSAndreas Gohr            try {
1916a18e0f4SAndreas Gohr                $embedding = $this->embedModel->getEmbedding($part);
192ad38c5fdSAndreas Gohr            } catch (\Exception $e) {
1937ebc7895Ssplitbrain                if ($this->logger instanceof CLI) {
194ad38c5fdSAndreas Gohr                    $this->logger->error(
195ad38c5fdSAndreas Gohr                        'Failed to get embedding for chunk of page {page}: {msg}',
196ad38c5fdSAndreas Gohr                        ['page' => $page, 'msg' => $e->getMessage()]
197ad38c5fdSAndreas Gohr                    );
198ad38c5fdSAndreas Gohr                }
199ad38c5fdSAndreas Gohr                continue;
200ad38c5fdSAndreas Gohr            }
2017ee8b02dSAndreas Gohr            $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding);
2027ee8b02dSAndreas Gohr            $firstChunkID++;
2038817535bSAndreas Gohr        }
2047ebc7895Ssplitbrain        if ($this->logger instanceof CLI) {
2057ebc7895Ssplitbrain            if ($chunkList !== []) {
206f8d5ae01SAndreas Gohr                $this->logger->success(
207f8d5ae01SAndreas Gohr                    '{id} split into {count} chunks',
208f8d5ae01SAndreas Gohr                    ['id' => $page, 'count' => count($chunkList)]
209f8d5ae01SAndreas Gohr                );
21093c1dbf4SAndreas Gohr            } else {
21193c1dbf4SAndreas Gohr                $this->logger->warning('{id} could not be split into chunks', ['id' => $page]);
21293c1dbf4SAndreas Gohr            }
2138817535bSAndreas Gohr        }
2147ee8b02dSAndreas Gohr        return $chunkList;
2158817535bSAndreas Gohr    }
2168817535bSAndreas Gohr
2179e81bea7SAndreas Gohr    /**
2189e81bea7SAndreas Gohr     * Do a nearest neighbor search for chunks similar to the given question
2199e81bea7SAndreas Gohr     *
2209e81bea7SAndreas Gohr     * Returns only chunks the current user is allowed to read, may return an empty result.
22168908844SAndreas Gohr     * The number of returned chunks depends on the MAX_CONTEXT_LEN setting.
2229e81bea7SAndreas Gohr     *
2239e81bea7SAndreas Gohr     * @param string $query The question
224e33a1d7aSAndreas Gohr     * @param string $lang Limit results to this language
2257ee8b02dSAndreas Gohr     * @return Chunk[]
2269e81bea7SAndreas Gohr     * @throws \Exception
2279e81bea7SAndreas Gohr     */
228e33a1d7aSAndreas Gohr    public function getSimilarChunks($query, $lang = '')
2298817535bSAndreas Gohr    {
2309e81bea7SAndreas Gohr        global $auth;
2316a18e0f4SAndreas Gohr        $vector = $this->embedModel->getEmbedding($query);
2328817535bSAndreas Gohr
233e3640be8SAndreas Gohr        $fetch = min(
23434a1c478SAndreas Gohr            ($this->chatModel->getMaxInputTokenLength() / $this->getChunkSize()),
23534a1c478SAndreas Gohr            $this->configContextChunks
236f6ef2e50SAndreas Gohr        );
237aee9b383SAndreas Gohr
238aee9b383SAndreas Gohr        $time = microtime(true);
239e33a1d7aSAndreas Gohr        $chunks = $this->storage->getSimilarChunks($vector, $lang, $fetch);
240*5f71c9bbSAndreas Gohr        $this->timeSpent = round(microtime(true) - $time, 2);
2417ebc7895Ssplitbrain        if ($this->logger instanceof CLI) {
242aee9b383SAndreas Gohr            $this->logger->info(
243aee9b383SAndreas Gohr                'Fetched {count} similar chunks from store in {time} seconds',
244*5f71c9bbSAndreas Gohr                ['count' => count($chunks), 'time' => $this->timeSpent]
245aee9b383SAndreas Gohr            );
246aee9b383SAndreas Gohr        }
24768908844SAndreas Gohr
24868908844SAndreas Gohr        $size = 0;
2498817535bSAndreas Gohr        $result = [];
2507ee8b02dSAndreas Gohr        foreach ($chunks as $chunk) {
2519e81bea7SAndreas Gohr            // filter out chunks the user is not allowed to read
2527ee8b02dSAndreas Gohr            if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue;
25368908844SAndreas Gohr
25468908844SAndreas Gohr            $chunkSize = count($this->getTokenEncoder()->encode($chunk->getText()));
25534a1c478SAndreas Gohr            if ($size + $chunkSize > $this->chatModel->getMaxInputTokenLength()) break; // we have enough
25668908844SAndreas Gohr
2579e81bea7SAndreas Gohr            $result[] = $chunk;
25868908844SAndreas Gohr            $size += $chunkSize;
2598817535bSAndreas Gohr        }
2608817535bSAndreas Gohr        return $result;
2618817535bSAndreas Gohr    }
2628817535bSAndreas Gohr
2635786be46SAndreas Gohr
2645786be46SAndreas Gohr    /**
2658817535bSAndreas Gohr     * @param $text
2668817535bSAndreas Gohr     * @return array
2678817535bSAndreas Gohr     * @throws \Exception
2688817535bSAndreas Gohr     * @todo support splitting too long sentences
2698817535bSAndreas Gohr     */
270ad38c5fdSAndreas Gohr    public function splitIntoChunks($text)
2718817535bSAndreas Gohr    {
2728817535bSAndreas Gohr        $sentenceSplitter = new Sentence();
27368908844SAndreas Gohr        $tiktok = $this->getTokenEncoder();
2748817535bSAndreas Gohr
2758817535bSAndreas Gohr        $chunks = [];
2768817535bSAndreas Gohr        $sentences = $sentenceSplitter->split($text);
2778817535bSAndreas Gohr
2788817535bSAndreas Gohr        $chunklen = 0;
2798817535bSAndreas Gohr        $chunk = '';
2808817535bSAndreas Gohr        while ($sentence = array_shift($sentences)) {
2818817535bSAndreas Gohr            $slen = count($tiktok->encode($sentence));
2826a18e0f4SAndreas Gohr            if ($slen > $this->getChunkSize()) {
2838817535bSAndreas Gohr                // sentence is too long, we need to split it further
284f8d5ae01SAndreas Gohr                if ($this->logger instanceof CLI) $this->logger->warning(
285f8d5ae01SAndreas Gohr                    'Sentence too long, splitting not implemented yet'
286f8d5ae01SAndreas Gohr                );
287ad38c5fdSAndreas Gohr                continue;
2888817535bSAndreas Gohr            }
2898817535bSAndreas Gohr
2906a18e0f4SAndreas Gohr            if ($chunklen + $slen < $this->getChunkSize()) {
2918817535bSAndreas Gohr                // add to current chunk
2928817535bSAndreas Gohr                $chunk .= $sentence;
2938817535bSAndreas Gohr                $chunklen += $slen;
29468908844SAndreas Gohr                // remember sentence for overlap check
29568908844SAndreas Gohr                $this->rememberSentence($sentence);
2968817535bSAndreas Gohr            } else {
29768908844SAndreas Gohr                // add current chunk to result
2988817535bSAndreas Gohr                $chunks[] = $chunk;
29968908844SAndreas Gohr
30068908844SAndreas Gohr                // start new chunk with remembered sentences
3017ebc7895Ssplitbrain                $chunk = implode(' ', $this->sentenceQueue);
30268908844SAndreas Gohr                $chunk .= $sentence;
30368908844SAndreas Gohr                $chunklen = count($tiktok->encode($chunk));
3048817535bSAndreas Gohr            }
3058817535bSAndreas Gohr        }
3068817535bSAndreas Gohr        $chunks[] = $chunk;
3078817535bSAndreas Gohr
3088817535bSAndreas Gohr        return $chunks;
3098817535bSAndreas Gohr    }
31068908844SAndreas Gohr
31168908844SAndreas Gohr    /**
31268908844SAndreas Gohr     * Add a sentence to the queue of remembered sentences
31368908844SAndreas Gohr     *
31468908844SAndreas Gohr     * @param string $sentence
31568908844SAndreas Gohr     * @return void
31668908844SAndreas Gohr     */
31768908844SAndreas Gohr    protected function rememberSentence($sentence)
31868908844SAndreas Gohr    {
31968908844SAndreas Gohr        // add sentence to queue
32068908844SAndreas Gohr        $this->sentenceQueue[] = $sentence;
32168908844SAndreas Gohr
32268908844SAndreas Gohr        // remove oldest sentences from queue until we are below the max overlap
32368908844SAndreas Gohr        $encoder = $this->getTokenEncoder();
3247ebc7895Ssplitbrain        while (count($encoder->encode(implode(' ', $this->sentenceQueue))) > self::MAX_OVERLAP_LEN) {
32568908844SAndreas Gohr            array_shift($this->sentenceQueue);
32668908844SAndreas Gohr        }
32768908844SAndreas Gohr    }
3288817535bSAndreas Gohr}
329