xref: /plugin/aichat/Embeddings.php (revision 5aa45b4d2b5251bf0407276721dbc6ffaf7dc9a0)
18817535bSAndreas Gohr<?php
28817535bSAndreas Gohr
38817535bSAndreas Gohrnamespace dokuwiki\plugin\aichat;
48817535bSAndreas Gohr
58817535bSAndreas Gohruse dokuwiki\Search\Indexer;
6ad38c5fdSAndreas Gohruse Hexogen\KDTree\Exception\ValidationException;
78817535bSAndreas Gohruse Hexogen\KDTree\FSKDTree;
88817535bSAndreas Gohruse Hexogen\KDTree\FSTreePersister;
98817535bSAndreas Gohruse Hexogen\KDTree\Item;
108817535bSAndreas Gohruse Hexogen\KDTree\ItemFactory;
118817535bSAndreas Gohruse Hexogen\KDTree\ItemList;
128817535bSAndreas Gohruse Hexogen\KDTree\KDTree;
138817535bSAndreas Gohruse Hexogen\KDTree\NearestSearch;
148817535bSAndreas Gohruse Hexogen\KDTree\Point;
152ecc089aSAndreas Gohruse splitbrain\phpcli\CLI;
168817535bSAndreas Gohruse TikToken\Encoder;
178817535bSAndreas Gohruse Vanderlee\Sentence\Sentence;
188817535bSAndreas Gohr
199da5f0dfSAndreas Gohr/**
209da5f0dfSAndreas Gohr * Manage the embeddings index
219da5f0dfSAndreas Gohr *
229da5f0dfSAndreas Gohr * Pages are split into chunks of 1000 tokens each. For each chunk the embedding vector is fetched from
239da5f0dfSAndreas Gohr * OpenAI and stored in a K-D Tree, chunk data is written to the file system.
249da5f0dfSAndreas Gohr */
258817535bSAndreas Gohrclass Embeddings
268817535bSAndreas Gohr{
278817535bSAndreas Gohr
28c4584168SAndreas Gohr    const MAX_TOKEN_LEN = 1000;
298817535bSAndreas Gohr    const INDEX_NAME = 'aichat';
308817535bSAndreas Gohr    const INDEX_FILE = 'index.bin';
318817535bSAndreas Gohr
322ecc089aSAndreas Gohr    /** @var OpenAI */
338817535bSAndreas Gohr    protected $openAI;
342ecc089aSAndreas Gohr    /** @var CLI|null */
352ecc089aSAndreas Gohr    protected $logger;
368817535bSAndreas Gohr
372ecc089aSAndreas Gohr    /**
382ecc089aSAndreas Gohr     * @param OpenAI $openAI
392ecc089aSAndreas Gohr     */
402ecc089aSAndreas Gohr    public function __construct(OpenAI $openAI)
418817535bSAndreas Gohr    {
428817535bSAndreas Gohr        $this->openAI = $openAI;
432ecc089aSAndreas Gohr    }
442ecc089aSAndreas Gohr
452ecc089aSAndreas Gohr    /**
462ecc089aSAndreas Gohr     * Add a logger instance
472ecc089aSAndreas Gohr     *
482ecc089aSAndreas Gohr     * @param CLI $logger
492ecc089aSAndreas Gohr     * @return void
502ecc089aSAndreas Gohr     */
512ecc089aSAndreas Gohr    public function setLogger(CLI $logger)
522ecc089aSAndreas Gohr    {
538817535bSAndreas Gohr        $this->logger = $logger;
548817535bSAndreas Gohr    }
558817535bSAndreas Gohr
562ecc089aSAndreas Gohr    /**
572ecc089aSAndreas Gohr     * Create a new K-D Tree from all pages
582ecc089aSAndreas Gohr     *
592ecc089aSAndreas Gohr     * Deletes the existing index
602ecc089aSAndreas Gohr     *
61ad38c5fdSAndreas Gohr     * @param string $skipRE Regular expression to filter out pages (full RE with delimiters)
622ecc089aSAndreas Gohr     * @return void
63ad38c5fdSAndreas Gohr     * @throws ValidationException
642ecc089aSAndreas Gohr     */
65ad38c5fdSAndreas Gohr    public function createNewIndex($skipRE = '')
668817535bSAndreas Gohr    {
678817535bSAndreas Gohr        $indexer = new Indexer();
688817535bSAndreas Gohr        $pages = $indexer->getPages();
698817535bSAndreas Gohr
708817535bSAndreas Gohr        $itemList = new ItemList(1536);
71*5aa45b4dSAndreas Gohr        foreach ($pages as $pid => $page) {
728817535bSAndreas Gohr            if (!page_exists($page)) continue;
736f9744f7SAndreas Gohr            if (isHiddenPage($page)) continue;
74ad38c5fdSAndreas Gohr            if ($skipRE && preg_match($skipRE, $page)) continue;
75*5aa45b4dSAndreas Gohr
76*5aa45b4dSAndreas Gohr            $chunkID = $pid * 100; // chunk IDs start at page ID * 100
77*5aa45b4dSAndreas Gohr
78*5aa45b4dSAndreas Gohr            $firstChunk = $this->getChunkFilePath($chunkID);
79*5aa45b4dSAndreas Gohr            if (@filemtime(wikiFN($page)) < @filemtime($firstChunk)) {
80*5aa45b4dSAndreas Gohr                // page is older than the chunks we have, reuse the existing chunks
81*5aa45b4dSAndreas Gohr                $this->reusePageChunks($itemList, $page, $chunkID);
82*5aa45b4dSAndreas Gohr            } else {
83*5aa45b4dSAndreas Gohr                // page is newer than the chunks we have, create new chunks
84*5aa45b4dSAndreas Gohr                $this->deletePageChunks($chunkID);
85*5aa45b4dSAndreas Gohr                $this->createPageChunks($itemList, $page, $chunkID);
86*5aa45b4dSAndreas Gohr            }
87*5aa45b4dSAndreas Gohr        }
88*5aa45b4dSAndreas Gohr
89*5aa45b4dSAndreas Gohr        $tree = new KDTree($itemList);
90*5aa45b4dSAndreas Gohr        if ($this->logger) {
91*5aa45b4dSAndreas Gohr            $this->logger->success('Created index with {count} items', ['count' => $tree->getItemCount()]);
92*5aa45b4dSAndreas Gohr        }
93*5aa45b4dSAndreas Gohr        $persister = new FSTreePersister($this->getStorageDir());
94*5aa45b4dSAndreas Gohr        $persister->convert($tree, self::INDEX_FILE);
95*5aa45b4dSAndreas Gohr    }
96*5aa45b4dSAndreas Gohr
97*5aa45b4dSAndreas Gohr    /**
98*5aa45b4dSAndreas Gohr     * Split the given page, fetch embedding vectors, save chunks and add them to the tree list
99*5aa45b4dSAndreas Gohr     *
100*5aa45b4dSAndreas Gohr     * @param ItemList $itemList The list to add the items to
101*5aa45b4dSAndreas Gohr     * @param string $page Name of the page to split
102*5aa45b4dSAndreas Gohr     * @param int $chunkID The ID of the first chunk of this page
103*5aa45b4dSAndreas Gohr     * @return void
104*5aa45b4dSAndreas Gohr     * @throws \Exception
105*5aa45b4dSAndreas Gohr     */
106*5aa45b4dSAndreas Gohr    protected function createPageChunks(ItemList $itemList, $page, $chunkID)
107*5aa45b4dSAndreas Gohr    {
1088817535bSAndreas Gohr        $text = rawWiki($page);
1098817535bSAndreas Gohr        $chunks = $this->splitIntoChunks($text);
1108817535bSAndreas Gohr        $meta = [
1118817535bSAndreas Gohr            'pageid' => $page,
1128817535bSAndreas Gohr        ];
1138817535bSAndreas Gohr        foreach ($chunks as $chunk) {
114ad38c5fdSAndreas Gohr            try {
1158817535bSAndreas Gohr                $embedding = $this->openAI->getEmbedding($chunk);
116ad38c5fdSAndreas Gohr            } catch (\Exception $e) {
117ad38c5fdSAndreas Gohr                if ($this->logger) {
118ad38c5fdSAndreas Gohr                    $this->logger->error(
119ad38c5fdSAndreas Gohr                        'Failed to get embedding for chunk of page {page}: {msg}',
120ad38c5fdSAndreas Gohr                        ['page' => $page, 'msg' => $e->getMessage()]
121ad38c5fdSAndreas Gohr                    );
122ad38c5fdSAndreas Gohr                }
123ad38c5fdSAndreas Gohr                continue;
124ad38c5fdSAndreas Gohr            }
125*5aa45b4dSAndreas Gohr            $item = new Item($chunkID, $embedding);
1268817535bSAndreas Gohr            $itemList->addItem($item);
127*5aa45b4dSAndreas Gohr            $this->saveChunk($item->getId(), $chunk, $embedding, $meta);
128*5aa45b4dSAndreas Gohr            $chunkID++;
1298817535bSAndreas Gohr        }
1308817535bSAndreas Gohr        if ($this->logger) {
131*5aa45b4dSAndreas Gohr            $this->logger->success('{id} split into {count} chunks', ['id' => $page, 'count' => count($chunks)]);
1328817535bSAndreas Gohr        }
1338817535bSAndreas Gohr    }
1348817535bSAndreas Gohr
135*5aa45b4dSAndreas Gohr    /**
136*5aa45b4dSAndreas Gohr     * Load the existing chunks for the given page and add them to the tree list
137*5aa45b4dSAndreas Gohr     *
138*5aa45b4dSAndreas Gohr     * @param ItemList $itemList The list to add the items to
139*5aa45b4dSAndreas Gohr     * @param string $page Name of the page to split
140*5aa45b4dSAndreas Gohr     * @param int $chunkID The ID of the first chunk of this page
141*5aa45b4dSAndreas Gohr     * @return void
142*5aa45b4dSAndreas Gohr     */
143*5aa45b4dSAndreas Gohr    protected function reusePageChunks(ItemList $itemList, $page, $chunkID)
144*5aa45b4dSAndreas Gohr    {
145*5aa45b4dSAndreas Gohr        for ($i = 0; $i < 100; $i++) {
146*5aa45b4dSAndreas Gohr            $chunk = $this->loadChunk($chunkID + $i);
147*5aa45b4dSAndreas Gohr            if (!$chunk) break;
148*5aa45b4dSAndreas Gohr            $item = new Item($chunkID, $chunk['embedding']);
149*5aa45b4dSAndreas Gohr            $itemList->addItem($item);
1508817535bSAndreas Gohr        }
151*5aa45b4dSAndreas Gohr        if ($this->logger) {
152*5aa45b4dSAndreas Gohr            $this->logger->success('{id} reused {count} chunks', ['id' => $page, 'count' => $i]);
153*5aa45b4dSAndreas Gohr        }
154*5aa45b4dSAndreas Gohr    }
155*5aa45b4dSAndreas Gohr
156*5aa45b4dSAndreas Gohr    /**
157*5aa45b4dSAndreas Gohr     * Delete all possibly existing chunks for one page (identified by the first chunk ID)
158*5aa45b4dSAndreas Gohr     *
159*5aa45b4dSAndreas Gohr     * @param int $chunkID The ID of the first chunk of this page
160*5aa45b4dSAndreas Gohr     * @return void
161*5aa45b4dSAndreas Gohr     */
162*5aa45b4dSAndreas Gohr    protected function deletePageChunks($chunkID)
163*5aa45b4dSAndreas Gohr    {
164*5aa45b4dSAndreas Gohr        for ($i = 0; $i < 100; $i++) {
165*5aa45b4dSAndreas Gohr            $chunk = $this->getChunkFilePath($chunkID + $i);
166*5aa45b4dSAndreas Gohr            if (!file_exists($chunk)) break;
167*5aa45b4dSAndreas Gohr            unlink($chunk);
168*5aa45b4dSAndreas Gohr        }
1698817535bSAndreas Gohr    }
1708817535bSAndreas Gohr
1719e81bea7SAndreas Gohr    /**
1729e81bea7SAndreas Gohr     * Do a nearest neighbor search for chunks similar to the given question
1739e81bea7SAndreas Gohr     *
1749e81bea7SAndreas Gohr     * Returns only chunks the current user is allowed to read, may return an empty result.
1759e81bea7SAndreas Gohr     *
1769e81bea7SAndreas Gohr     * @param string $query The question
1779e81bea7SAndreas Gohr     * @param int $limit The number of results to return
1789e81bea7SAndreas Gohr     * @return array
1799e81bea7SAndreas Gohr     * @throws \Exception
1809e81bea7SAndreas Gohr     */
1818817535bSAndreas Gohr    public function getSimilarChunks($query, $limit = 4)
1828817535bSAndreas Gohr    {
1839e81bea7SAndreas Gohr        global $auth;
1848817535bSAndreas Gohr        $embedding = $this->openAI->getEmbedding($query);
1858817535bSAndreas Gohr
1868817535bSAndreas Gohr        $file = $this->getStorageDir() . self::INDEX_FILE;
1878817535bSAndreas Gohr        $fsTree = new FSKDTree($file, new ItemFactory());
1888817535bSAndreas Gohr        $fsSearcher = new NearestSearch($fsTree);
1899e81bea7SAndreas Gohr        $items = $fsSearcher->search(new Point($embedding), $limit * 2); // we get twice as many as needed
1908817535bSAndreas Gohr
1918817535bSAndreas Gohr        $result = [];
1928817535bSAndreas Gohr        foreach ($items as $item) {
1939e81bea7SAndreas Gohr            $chunk = $this->loadChunk($item->getId());
1949e81bea7SAndreas Gohr            // filter out chunks the user is not allowed to read
1959e81bea7SAndreas Gohr            if ($auth && auth_quickaclcheck($chunk['meta']['pageid']) < AUTH_READ) continue;
1969e81bea7SAndreas Gohr            $result[] = $chunk;
1979e81bea7SAndreas Gohr            if (count($result) >= $limit) break;
1988817535bSAndreas Gohr        }
1998817535bSAndreas Gohr        return $result;
2008817535bSAndreas Gohr    }
2018817535bSAndreas Gohr
2028817535bSAndreas Gohr    /**
2038817535bSAndreas Gohr     * @param $text
2048817535bSAndreas Gohr     * @return array
2058817535bSAndreas Gohr     * @throws \Exception
2068817535bSAndreas Gohr     * @todo maybe add overlap support
2078817535bSAndreas Gohr     * @todo support splitting too long sentences
2088817535bSAndreas Gohr     */
209ad38c5fdSAndreas Gohr    public function splitIntoChunks($text)
2108817535bSAndreas Gohr    {
2118817535bSAndreas Gohr        $sentenceSplitter = new Sentence();
2128817535bSAndreas Gohr        $tiktok = new Encoder();
2138817535bSAndreas Gohr
2148817535bSAndreas Gohr        $chunks = [];
2158817535bSAndreas Gohr        $sentences = $sentenceSplitter->split($text);
2168817535bSAndreas Gohr
2178817535bSAndreas Gohr        $chunklen = 0;
2188817535bSAndreas Gohr        $chunk = '';
2198817535bSAndreas Gohr        while ($sentence = array_shift($sentences)) {
2208817535bSAndreas Gohr            $slen = count($tiktok->encode($sentence));
2218817535bSAndreas Gohr            if ($slen > self::MAX_TOKEN_LEN) {
2228817535bSAndreas Gohr                // sentence is too long, we need to split it further
223ad38c5fdSAndreas Gohr                if ($this->logger) $this->logger->warning('Sentence too long, splitting not implemented yet');
224ad38c5fdSAndreas Gohr                continue;
2258817535bSAndreas Gohr            }
2268817535bSAndreas Gohr
2278817535bSAndreas Gohr            if ($chunklen + $slen < self::MAX_TOKEN_LEN) {
2288817535bSAndreas Gohr                // add to current chunk
2298817535bSAndreas Gohr                $chunk .= $sentence;
2308817535bSAndreas Gohr                $chunklen += $slen;
2318817535bSAndreas Gohr            } else {
2328817535bSAndreas Gohr                // start new chunk
2338817535bSAndreas Gohr                $chunks[] = $chunk;
2348817535bSAndreas Gohr                $chunk = $sentence;
2358817535bSAndreas Gohr                $chunklen = $slen;
2368817535bSAndreas Gohr            }
2378817535bSAndreas Gohr        }
2388817535bSAndreas Gohr        $chunks[] = $chunk;
2398817535bSAndreas Gohr
2408817535bSAndreas Gohr        return $chunks;
2418817535bSAndreas Gohr    }
2428817535bSAndreas Gohr
2439da5f0dfSAndreas Gohr    /**
2449da5f0dfSAndreas Gohr     * Store additional chunk data in the file system
2459da5f0dfSAndreas Gohr     *
2469da5f0dfSAndreas Gohr     * @param int $id The chunk id in the K-D tree
2479da5f0dfSAndreas Gohr     * @param string $text raw text of the chunk
248*5aa45b4dSAndreas Gohr     * @param float[] $embedding embedding vector of the chunk
2499da5f0dfSAndreas Gohr     * @param array $meta meta data to store with the chunk
2509da5f0dfSAndreas Gohr     * @return void
2519da5f0dfSAndreas Gohr     */
252*5aa45b4dSAndreas Gohr    public function saveChunk($id, $text, $embedding, $meta = [])
2538817535bSAndreas Gohr    {
2548817535bSAndreas Gohr        $data = [
2558817535bSAndreas Gohr            'id' => $id,
2568817535bSAndreas Gohr            'text' => $text,
257*5aa45b4dSAndreas Gohr            'embedding' => $embedding,
2588817535bSAndreas Gohr            'meta' => $meta,
2598817535bSAndreas Gohr        ];
2608817535bSAndreas Gohr
261*5aa45b4dSAndreas Gohr        $chunkfile = $this->getChunkFilePath($id);
2628817535bSAndreas Gohr        io_saveFile($chunkfile, json_encode($data));
2638817535bSAndreas Gohr    }
2648817535bSAndreas Gohr
2659da5f0dfSAndreas Gohr    /**
2669da5f0dfSAndreas Gohr     * Load chunk data from the file system
2679da5f0dfSAndreas Gohr     *
2689da5f0dfSAndreas Gohr     * @param int $id
269*5aa45b4dSAndreas Gohr     * @return array|false The chunk data [id, text, embedding, meta => []], false if not found
2709da5f0dfSAndreas Gohr     */
2718817535bSAndreas Gohr    public function loadChunk($id)
2728817535bSAndreas Gohr    {
273*5aa45b4dSAndreas Gohr        $chunkfile = $this->getChunkFilePath($id);
274*5aa45b4dSAndreas Gohr        if (!file_exists($chunkfile)) return false;
2758817535bSAndreas Gohr        return json_decode(io_readFile($chunkfile, false), true);
2768817535bSAndreas Gohr    }
2778817535bSAndreas Gohr
2789da5f0dfSAndreas Gohr    /**
279*5aa45b4dSAndreas Gohr     * Return the path to the chunk file
280*5aa45b4dSAndreas Gohr     *
281*5aa45b4dSAndreas Gohr     * @param $id
282*5aa45b4dSAndreas Gohr     * @return string
283*5aa45b4dSAndreas Gohr     */
284*5aa45b4dSAndreas Gohr    protected function getChunkFilePath($id)
285*5aa45b4dSAndreas Gohr    {
286*5aa45b4dSAndreas Gohr        $id = dechex($id); // use hexadecimal for shorter file names
287*5aa45b4dSAndreas Gohr        return $this->getStorageDir('chunk') . $id . '.json';
288*5aa45b4dSAndreas Gohr    }
289*5aa45b4dSAndreas Gohr
290*5aa45b4dSAndreas Gohr    /**
2919da5f0dfSAndreas Gohr     * Return the path to where the K-D tree and chunk data is stored
2929da5f0dfSAndreas Gohr     *
2939da5f0dfSAndreas Gohr     * @param string $subdir
2949da5f0dfSAndreas Gohr     * @return string
2959da5f0dfSAndreas Gohr     */
2968817535bSAndreas Gohr    protected function getStorageDir($subdir = '')
2978817535bSAndreas Gohr    {
2988817535bSAndreas Gohr        global $conf;
2998817535bSAndreas Gohr        $dir = $conf['indexdir'] . '/' . self::INDEX_NAME . '/';
3008817535bSAndreas Gohr        if ($subdir) $dir .= $subdir . '/';
3018817535bSAndreas Gohr        io_mkdir_p($dir);
3028817535bSAndreas Gohr        return $dir;
3038817535bSAndreas Gohr    }
3048817535bSAndreas Gohr}
305