xref: /plugin/aichat/Embeddings.php (revision 072e009990858d649f31eceb61c1bc980d28f40c)
18817535bSAndreas Gohr<?php
28817535bSAndreas Gohr
38817535bSAndreas Gohrnamespace dokuwiki\plugin\aichat;
48817535bSAndreas Gohr
5ab1f8ddeSAndreas Gohruse dokuwiki\Extension\Event;
6661701eeSAndreas Gohruse dokuwiki\File\PageResolver;
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{
23294a9eafSAndreas Gohr    /** @var ChatInterface */
246a18e0f4SAndreas Gohr    protected $chatModel;
256a18e0f4SAndreas Gohr
26294a9eafSAndreas Gohr    /** @var EmbeddingInterface */
276a18e0f4SAndreas Gohr    protected $embedModel;
286a18e0f4SAndreas Gohr
292ecc089aSAndreas Gohr    /** @var CLI|null */
302ecc089aSAndreas Gohr    protected $logger;
3168908844SAndreas Gohr    /** @var Encoder */
3268908844SAndreas Gohr    protected $tokenEncoder;
338817535bSAndreas Gohr
347ee8b02dSAndreas Gohr    /** @var AbstractStorage */
357ee8b02dSAndreas Gohr    protected $storage;
367ee8b02dSAndreas Gohr
3768908844SAndreas Gohr    /** @var array remember sentences when chunking */
3868908844SAndreas Gohr    private $sentenceQueue = [];
3968908844SAndreas Gohr
40c2b7a1f7SAndreas Gohr    /** @var int the time spent for the last similar chunk retrieval */
41c2b7a1f7SAndreas Gohr    public $timeSpent = 0;
42c2b7a1f7SAndreas Gohr
4334a1c478SAndreas Gohr    protected $configChunkSize;
4434a1c478SAndreas Gohr    protected $configContextChunks;
45720bb43fSAndreas Gohr    protected $similarityThreshold;
4634a1c478SAndreas Gohr
4734a1c478SAndreas Gohr    /**
4834a1c478SAndreas Gohr     * Embeddings constructor.
4934a1c478SAndreas Gohr     *
5034a1c478SAndreas Gohr     * @param ChatInterface $chatModel
5134a1c478SAndreas Gohr     * @param EmbeddingInterface $embedModel
5234a1c478SAndreas Gohr     * @param AbstractStorage $storage
5334a1c478SAndreas Gohr     * @param array $config The plugin configuration
5434a1c478SAndreas Gohr     */
556a18e0f4SAndreas Gohr    public function __construct(
56294a9eafSAndreas Gohr        ChatInterface      $chatModel,
57294a9eafSAndreas Gohr        EmbeddingInterface $embedModel,
5834a1c478SAndreas Gohr        AbstractStorage    $storage,
5934a1c478SAndreas Gohr                           $config
60aa6bbe75SAndreas Gohr    )
61aa6bbe75SAndreas Gohr    {
626a18e0f4SAndreas Gohr        $this->chatModel = $chatModel;
636a18e0f4SAndreas Gohr        $this->embedModel = $embedModel;
64f6ef2e50SAndreas Gohr        $this->storage = $storage;
6534a1c478SAndreas Gohr        $this->configChunkSize = $config['chunkSize'];
6634a1c478SAndreas Gohr        $this->configContextChunks = $config['contextChunks'];
67720bb43fSAndreas Gohr        $this->similarityThreshold = $config['similarityThreshold'] / 100;
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    /**
81aa6bbe75SAndreas Gohr     * Override the number of used context chunks
82aa6bbe75SAndreas Gohr     *
83aa6bbe75SAndreas Gohr     * @param int $max
84aa6bbe75SAndreas Gohr     * @return void
85aa6bbe75SAndreas Gohr     */
86aa6bbe75SAndreas Gohr    public function setConfigContextChunks(int $max)
87aa6bbe75SAndreas Gohr    {
88aa6bbe75SAndreas Gohr        if ($max <= 0) throw new \InvalidArgumentException('max context chunks must be greater than 0');
89aa6bbe75SAndreas Gohr        $this->configContextChunks = $max;
90aa6bbe75SAndreas Gohr    }
91aa6bbe75SAndreas Gohr
92aa6bbe75SAndreas Gohr    /**
93aa6bbe75SAndreas Gohr     * Override the similiarity threshold
94aa6bbe75SAndreas Gohr     *
95aa6bbe75SAndreas Gohr     * @param float $threshold
96aa6bbe75SAndreas Gohr     * @return void
97aa6bbe75SAndreas Gohr     */
98aa6bbe75SAndreas Gohr    public function setSimilarityThreshold(float $threshold)
99aa6bbe75SAndreas Gohr    {
100aa6bbe75SAndreas Gohr        if ($threshold < 0 || $threshold > 1) throw new \InvalidArgumentException('threshold must be between 0 and 1');
101aa6bbe75SAndreas Gohr        $this->similarityThreshold = $threshold;
102aa6bbe75SAndreas Gohr    }
103aa6bbe75SAndreas Gohr
104aa6bbe75SAndreas Gohr    /**
1052ecc089aSAndreas Gohr     * Add a logger instance
1062ecc089aSAndreas Gohr     *
1072ecc089aSAndreas Gohr     * @return void
1082ecc089aSAndreas Gohr     */
1092ecc089aSAndreas Gohr    public function setLogger(CLI $logger)
1102ecc089aSAndreas Gohr    {
1118817535bSAndreas Gohr        $this->logger = $logger;
1128817535bSAndreas Gohr    }
1138817535bSAndreas Gohr
1142ecc089aSAndreas Gohr    /**
11568908844SAndreas Gohr     * Get the token encoder instance
11668908844SAndreas Gohr     *
11768908844SAndreas Gohr     * @return Encoder
11868908844SAndreas Gohr     */
11968908844SAndreas Gohr    public function getTokenEncoder()
12068908844SAndreas Gohr    {
1217ebc7895Ssplitbrain        if (!$this->tokenEncoder instanceof Encoder) {
12268908844SAndreas Gohr            $this->tokenEncoder = new Encoder();
12368908844SAndreas Gohr        }
12468908844SAndreas Gohr        return $this->tokenEncoder;
12568908844SAndreas Gohr    }
12668908844SAndreas Gohr
12768908844SAndreas Gohr    /**
1286a18e0f4SAndreas Gohr     * Return the chunk size to use
1296a18e0f4SAndreas Gohr     *
1306a18e0f4SAndreas Gohr     * @return int
1316a18e0f4SAndreas Gohr     */
1326a18e0f4SAndreas Gohr    public function getChunkSize()
1336a18e0f4SAndreas Gohr    {
1346a18e0f4SAndreas Gohr        return min(
13534a1c478SAndreas Gohr            floor($this->chatModel->getMaxInputTokenLength() / 4), // be able to fit 4 chunks into the max input
13634a1c478SAndreas Gohr            floor($this->embedModel->getMaxInputTokenLength() * 0.9), // only use 90% of the embedding model to be safe
13734a1c478SAndreas Gohr            $this->configChunkSize, // this is usually the smallest
1386a18e0f4SAndreas Gohr        );
1396a18e0f4SAndreas Gohr    }
1406a18e0f4SAndreas Gohr
1416a18e0f4SAndreas Gohr    /**
1425284515dSAndreas Gohr     * Update the embeddings storage
1432ecc089aSAndreas Gohr     *
144ad38c5fdSAndreas Gohr     * @param string $skipRE Regular expression to filter out pages (full RE with delimiters)
145d5c102b3SAndreas Gohr     * @param string $matchRE Regular expression pages have to match to be included (full RE with delimiters)
1465284515dSAndreas Gohr     * @param bool $clear Should any existing storage be cleared before updating?
1472ecc089aSAndreas Gohr     * @return void
1485284515dSAndreas Gohr     * @throws \Exception
1492ecc089aSAndreas Gohr     */
150d5c102b3SAndreas Gohr    public function createNewIndex($skipRE = '', $matchRE = '', $clear = false)
1518817535bSAndreas Gohr    {
1528817535bSAndreas Gohr        $indexer = new Indexer();
1538817535bSAndreas Gohr        $pages = $indexer->getPages();
1548817535bSAndreas Gohr
155f6ef2e50SAndreas Gohr        $this->storage->startCreation($clear);
1565aa45b4dSAndreas Gohr        foreach ($pages as $pid => $page) {
1575aa45b4dSAndreas Gohr            $chunkID = $pid * 100; // chunk IDs start at page ID * 100
1585aa45b4dSAndreas Gohr
1595284515dSAndreas Gohr            if (
1605284515dSAndreas Gohr                !page_exists($page) ||
1615284515dSAndreas Gohr                isHiddenPage($page) ||
1624e206c13SAndreas Gohr                filesize(wikiFN($page)) < 150 || // skip very small pages
163d5c102b3SAndreas Gohr                ($skipRE && preg_match($skipRE, (string)$page)) ||
164d5c102b3SAndreas Gohr                ($matchRE && !preg_match($matchRE, ":$page"))
1655284515dSAndreas Gohr            ) {
1665284515dSAndreas Gohr                // this page should not be in the index (anymore)
1675284515dSAndreas Gohr                $this->storage->deletePageChunks($page, $chunkID);
1685284515dSAndreas Gohr                continue;
1695284515dSAndreas Gohr            }
1705284515dSAndreas Gohr
1717ee8b02dSAndreas Gohr            $firstChunk = $this->storage->getChunk($chunkID);
1727ee8b02dSAndreas Gohr            if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) {
1735aa45b4dSAndreas Gohr                // page is older than the chunks we have, reuse the existing chunks
1747ee8b02dSAndreas Gohr                $this->storage->reusePageChunks($page, $chunkID);
1757ebc7895Ssplitbrain                if ($this->logger instanceof CLI) $this->logger->info("Reusing chunks for $page");
1765aa45b4dSAndreas Gohr            } else {
1775aa45b4dSAndreas Gohr                // page is newer than the chunks we have, create new chunks
1787ee8b02dSAndreas Gohr                $this->storage->deletePageChunks($page, $chunkID);
179ecb0a423SAndreas Gohr                $chunks = $this->createPageChunks($page, $chunkID);
180ecb0a423SAndreas Gohr                if ($chunks) $this->storage->addPageChunks($chunks);
1815aa45b4dSAndreas Gohr            }
1825aa45b4dSAndreas Gohr        }
1837ee8b02dSAndreas Gohr        $this->storage->finalizeCreation();
1845aa45b4dSAndreas Gohr    }
1855aa45b4dSAndreas Gohr
1865aa45b4dSAndreas Gohr    /**
1877ee8b02dSAndreas Gohr     * Split the given page, fetch embedding vectors and return Chunks
1885aa45b4dSAndreas Gohr     *
18988305719SAndreas Gohr     * Will use the text renderer plugin if available to get the rendered text.
19088305719SAndreas Gohr     * Otherwise the raw wiki text is used.
19188305719SAndreas Gohr     *
1925aa45b4dSAndreas Gohr     * @param string $page Name of the page to split
1937ee8b02dSAndreas Gohr     * @param int $firstChunkID The ID of the first chunk of this page
1947ee8b02dSAndreas Gohr     * @return Chunk[] A list of chunks created for this page
195ab1f8ddeSAndreas Gohr     * @emits INDEXER_PAGE_ADD support plugins that add additional data to the page
1965aa45b4dSAndreas Gohr     * @throws \Exception
1975aa45b4dSAndreas Gohr     */
198ab1f8ddeSAndreas Gohr    public function createPageChunks($page, $firstChunkID)
1995aa45b4dSAndreas Gohr    {
2007ee8b02dSAndreas Gohr        $chunkList = [];
20188305719SAndreas Gohr
20288305719SAndreas Gohr        global $ID;
20388305719SAndreas Gohr        $ID = $page;
204303d0c59SAndreas Gohr        try {
205661701eeSAndreas Gohr            $text = p_cached_output(wikiFN($page), 'aichat', $page);
206303d0c59SAndreas Gohr        } catch (\Throwable $e) {
207303d0c59SAndreas Gohr            if ($this->logger) $this->logger->error(
208661701eeSAndreas Gohr                'Failed to render page {page}. Using raw text instead. {msg}',
209303d0c59SAndreas Gohr                ['page' => $page, 'msg' => $e->getMessage()]
210303d0c59SAndreas Gohr            );
211303d0c59SAndreas Gohr            $text = rawWiki($page);
212303d0c59SAndreas Gohr        }
213661701eeSAndreas Gohr
214661701eeSAndreas Gohr        $crumbs = $this->breadcrumbTrail($page);
21588305719SAndreas Gohr
216ab1f8ddeSAndreas Gohr        // allow plugins to modify the text before splitting
217ab1f8ddeSAndreas Gohr        $eventData = [
218ab1f8ddeSAndreas Gohr            'page' => $page,
219ab1f8ddeSAndreas Gohr            'body' => '',
220ab1f8ddeSAndreas Gohr            'metadata' => ['title' => $page, 'relation_references' => []],
221ab1f8ddeSAndreas Gohr        ];
222ab1f8ddeSAndreas Gohr        $event = new Event('INDEXER_PAGE_ADD', $eventData);
223ab1f8ddeSAndreas Gohr        if ($event->advise_before()) {
224ab1f8ddeSAndreas Gohr            $text = $eventData['body'] . ' ' . $text;
225ab1f8ddeSAndreas Gohr        } else {
226ab1f8ddeSAndreas Gohr            $text = $eventData['body'];
227ab1f8ddeSAndreas Gohr        }
228ab1f8ddeSAndreas Gohr
229*072e0099SAndreas Gohr        $splitter = new TextSplitter($this->getChunkSize(), $this->getTokenEncoder());
230*072e0099SAndreas Gohr        $parts = $splitter->splitIntoChunks($text);
2317ee8b02dSAndreas Gohr        foreach ($parts as $part) {
232*072e0099SAndreas Gohr            if (trim($part) === '') continue; // skip empty chunks
23393c1dbf4SAndreas Gohr
234661701eeSAndreas Gohr            $part = $crumbs . "\n\n" . $part; // add breadcrumbs to each chunk
235661701eeSAndreas Gohr
236ad38c5fdSAndreas Gohr            try {
2376a18e0f4SAndreas Gohr                $embedding = $this->embedModel->getEmbedding($part);
238ad38c5fdSAndreas Gohr            } catch (\Exception $e) {
2397ebc7895Ssplitbrain                if ($this->logger instanceof CLI) {
240ad38c5fdSAndreas Gohr                    $this->logger->error(
241ad38c5fdSAndreas Gohr                        'Failed to get embedding for chunk of page {page}: {msg}',
242ad38c5fdSAndreas Gohr                        ['page' => $page, 'msg' => $e->getMessage()]
243ad38c5fdSAndreas Gohr                    );
244ad38c5fdSAndreas Gohr                }
245ad38c5fdSAndreas Gohr                continue;
246ad38c5fdSAndreas Gohr            }
2477ee8b02dSAndreas Gohr            $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding);
2487ee8b02dSAndreas Gohr            $firstChunkID++;
2498817535bSAndreas Gohr        }
2507ebc7895Ssplitbrain        if ($this->logger instanceof CLI) {
2517ebc7895Ssplitbrain            if ($chunkList !== []) {
252f8d5ae01SAndreas Gohr                $this->logger->success(
253f8d5ae01SAndreas Gohr                    '{id} split into {count} chunks',
254f8d5ae01SAndreas Gohr                    ['id' => $page, 'count' => count($chunkList)]
255f8d5ae01SAndreas Gohr                );
25693c1dbf4SAndreas Gohr            } else {
25793c1dbf4SAndreas Gohr                $this->logger->warning('{id} could not be split into chunks', ['id' => $page]);
25893c1dbf4SAndreas Gohr            }
2598817535bSAndreas Gohr        }
2607ee8b02dSAndreas Gohr        return $chunkList;
2618817535bSAndreas Gohr    }
2628817535bSAndreas Gohr
2639e81bea7SAndreas Gohr    /**
2649e81bea7SAndreas Gohr     * Do a nearest neighbor search for chunks similar to the given question
2659e81bea7SAndreas Gohr     *
2669e81bea7SAndreas Gohr     * Returns only chunks the current user is allowed to read, may return an empty result.
26768908844SAndreas Gohr     * The number of returned chunks depends on the MAX_CONTEXT_LEN setting.
2689e81bea7SAndreas Gohr     *
2699e81bea7SAndreas Gohr     * @param string $query The question
270e33a1d7aSAndreas Gohr     * @param string $lang Limit results to this language
271aa6bbe75SAndreas Gohr     * @param bool $limits Apply chat token limits to the number of chunks returned?
2727ee8b02dSAndreas Gohr     * @return Chunk[]
2739e81bea7SAndreas Gohr     * @throws \Exception
2749e81bea7SAndreas Gohr     */
275aa6bbe75SAndreas Gohr    public function getSimilarChunks($query, $lang = '', $limits = true)
2768817535bSAndreas Gohr    {
2779e81bea7SAndreas Gohr        global $auth;
2786a18e0f4SAndreas Gohr        $vector = $this->embedModel->getEmbedding($query);
2798817535bSAndreas Gohr
280aa6bbe75SAndreas Gohr        if ($limits) {
281e3640be8SAndreas Gohr            $fetch = min(
28234a1c478SAndreas Gohr                ($this->chatModel->getMaxInputTokenLength() / $this->getChunkSize()),
28334a1c478SAndreas Gohr                $this->configContextChunks
284f6ef2e50SAndreas Gohr            );
285aa6bbe75SAndreas Gohr        } else {
286aa6bbe75SAndreas Gohr            $fetch = $this->configContextChunks;
287aa6bbe75SAndreas Gohr        }
288aee9b383SAndreas Gohr
289aee9b383SAndreas Gohr        $time = microtime(true);
290e33a1d7aSAndreas Gohr        $chunks = $this->storage->getSimilarChunks($vector, $lang, $fetch);
2915f71c9bbSAndreas Gohr        $this->timeSpent = round(microtime(true) - $time, 2);
2927ebc7895Ssplitbrain        if ($this->logger instanceof CLI) {
293aee9b383SAndreas Gohr            $this->logger->info(
294c2f55081SAndreas Gohr                'Fetched {count} similar chunks from store in {time} seconds. Query: {query}',
295c2f55081SAndreas Gohr                ['count' => count($chunks), 'time' => $this->timeSpent, 'query' => $query]
296aee9b383SAndreas Gohr            );
297aee9b383SAndreas Gohr        }
29868908844SAndreas Gohr
29968908844SAndreas Gohr        $size = 0;
3008817535bSAndreas Gohr        $result = [];
3017ee8b02dSAndreas Gohr        foreach ($chunks as $chunk) {
3029e81bea7SAndreas Gohr            // filter out chunks the user is not allowed to read
3037ee8b02dSAndreas Gohr            if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue;
304720bb43fSAndreas Gohr            if ($chunk->getScore() < $this->similarityThreshold) continue;
30568908844SAndreas Gohr
306aa6bbe75SAndreas Gohr            if ($limits) {
30768908844SAndreas Gohr                $chunkSize = count($this->getTokenEncoder()->encode($chunk->getText()));
30834a1c478SAndreas Gohr                if ($size + $chunkSize > $this->chatModel->getMaxInputTokenLength()) break; // we have enough
309aa6bbe75SAndreas Gohr            }
31068908844SAndreas Gohr
3119e81bea7SAndreas Gohr            $result[] = $chunk;
312aa6bbe75SAndreas Gohr            $size += $chunkSize ?? 0;
313aa6bbe75SAndreas Gohr
314aa6bbe75SAndreas Gohr            if (count($result) >= $this->configContextChunks) break; // we have enough
3158817535bSAndreas Gohr        }
3168817535bSAndreas Gohr        return $result;
3178817535bSAndreas Gohr    }
3188817535bSAndreas Gohr
319661701eeSAndreas Gohr    /**
320661701eeSAndreas Gohr     * Create a breadcrumb trail for the given page
321661701eeSAndreas Gohr     *
322661701eeSAndreas Gohr     * Uses the first heading of each namespace and the page itself. This is added as a prefix to
323661701eeSAndreas Gohr     * each chunk to give the AI some context.
324661701eeSAndreas Gohr     *
325661701eeSAndreas Gohr     * @param string $id
326661701eeSAndreas Gohr     * @return string
327661701eeSAndreas Gohr     */
328661701eeSAndreas Gohr    protected function breadcrumbTrail($id)
329661701eeSAndreas Gohr    {
330661701eeSAndreas Gohr        $namespaces = explode(':', getNS($id));
331661701eeSAndreas Gohr        $resolver = new PageResolver($id);
332661701eeSAndreas Gohr        $crumbs = [];
333661701eeSAndreas Gohr
334661701eeSAndreas Gohr        // all namespaces
335661701eeSAndreas Gohr        $check = '';
336661701eeSAndreas Gohr        foreach ($namespaces as $namespace) {
337661701eeSAndreas Gohr            $check .= $namespace . ':';
338661701eeSAndreas Gohr            $page = $resolver->resolveId($check);
339661701eeSAndreas Gohr            $title = p_get_first_heading($page);
340661701eeSAndreas Gohr            $crumbs[] = $title ? "$title ($namespace)" : $namespace;
341661701eeSAndreas Gohr        }
342661701eeSAndreas Gohr
343661701eeSAndreas Gohr        // the page itself
344661701eeSAndreas Gohr        $title = p_get_first_heading($id);
345661701eeSAndreas Gohr        $page = noNS($id);
346661701eeSAndreas Gohr        $crumbs[] = $title ? "$title ($page)" : $page;
347661701eeSAndreas Gohr
348661701eeSAndreas Gohr        return implode(' » ', $crumbs);
349661701eeSAndreas Gohr    }
3508817535bSAndreas Gohr}
351