xref: /plugin/aichat/Embeddings.php (revision 4e206c13fae6bfebe32342c2c7cff2cf7d1ff4e0)
1<?php
2
3namespace dokuwiki\plugin\aichat;
4
5use dokuwiki\plugin\aichat\backend\AbstractStorage;
6use dokuwiki\plugin\aichat\backend\Chunk;
7use dokuwiki\plugin\aichat\backend\KDTreeStorage;
8use dokuwiki\plugin\aichat\backend\SQLiteStorage;
9use dokuwiki\Search\Indexer;
10use Hexogen\KDTree\Exception\ValidationException;
11use splitbrain\phpcli\CLI;
12use TikToken\Encoder;
13use Vanderlee\Sentence\Sentence;
14
15/**
16 * Manage the embeddings index
17 *
18 * Pages are split into chunks of 1000 tokens each. For each chunk the embedding vector is fetched from
19 * OpenAI and stored in the Storage backend.
20 */
21class Embeddings
22{
23
24    const MAX_TOKEN_LEN = 1000;
25
26
27    /** @var OpenAI */
28    protected $openAI;
29    /** @var CLI|null */
30    protected $logger;
31
32    /** @var AbstractStorage */
33    protected $storage;
34
35    /**
36     * @param OpenAI $openAI
37     */
38    public function __construct(OpenAI $openAI)
39    {
40        $this->openAI = $openAI;
41        //$this->storage = new KDTreeStorage(); // FIXME make configurable
42        $this->storage = new SQLiteStorage(); // FIXME make configurable
43    }
44
45    /**
46     * Access storage
47     *
48     * @return AbstractStorage
49     */
50    public function getStorage()
51    {
52        return $this->storage;
53    }
54
55    /**
56     * Add a logger instance
57     *
58     * @param CLI $logger
59     * @return void
60     */
61    public function setLogger(CLI $logger)
62    {
63        $this->logger = $logger;
64    }
65
66    /**
67     * Update the embeddings storage
68     *
69     * @param string $skipRE Regular expression to filter out pages (full RE with delimiters)
70     * @param bool $clear Should any existing storage be cleared before updating?
71     * @return void
72     * @throws \Exception
73     */
74    public function createNewIndex($skipRE = '', $clear = false)
75    {
76        $indexer = new Indexer();
77        $pages = $indexer->getPages();
78
79        $this->storage->startCreation(1536, $clear);
80        foreach ($pages as $pid => $page) {
81            $chunkID = $pid * 100; // chunk IDs start at page ID * 100
82
83            if (
84                !page_exists($page) ||
85                isHiddenPage($page) ||
86                filesize(wikiFN($page)) < 150 || // skip very small pages
87                ($skipRE && preg_match($skipRE, $page))
88            ) {
89                // this page should not be in the index (anymore)
90                $this->storage->deletePageChunks($page, $chunkID);
91                continue;
92            }
93
94            $firstChunk = $this->storage->getChunk($chunkID);
95            if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) {
96                // page is older than the chunks we have, reuse the existing chunks
97                $this->storage->reusePageChunks($page, $chunkID);
98                if($this->logger) $this->logger->info("Reusing chunks for $page");
99            } else {
100                // page is newer than the chunks we have, create new chunks
101                $this->storage->deletePageChunks($page, $chunkID);
102                $this->storage->addPageChunks($this->createPageChunks($page, $chunkID));
103            }
104        }
105        $this->storage->finalizeCreation();
106    }
107
108    /**
109     * Split the given page, fetch embedding vectors and return Chunks
110     *
111     * @param string $page Name of the page to split
112     * @param int $firstChunkID The ID of the first chunk of this page
113     * @return Chunk[] A list of chunks created for this page
114     * @throws \Exception
115     */
116    protected function createPageChunks($page, $firstChunkID)
117    {
118        $chunkList = [];
119        $parts = $this->splitIntoChunks(rawWiki($page));
120        foreach ($parts as $part) {
121            try {
122                $embedding = $this->openAI->getEmbedding($part);
123            } catch (\Exception $e) {
124                if ($this->logger) {
125                    $this->logger->error(
126                        'Failed to get embedding for chunk of page {page}: {msg}',
127                        ['page' => $page, 'msg' => $e->getMessage()]
128                    );
129                }
130                continue;
131            }
132            $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding);
133            $firstChunkID++;
134        }
135        if ($this->logger) {
136            $this->logger->success('{id} split into {count} chunks', ['id' => $page, 'count' => count($parts)]);
137        }
138        return $chunkList;
139    }
140
141    /**
142     * Do a nearest neighbor search for chunks similar to the given question
143     *
144     * Returns only chunks the current user is allowed to read, may return an empty result.
145     *
146     * @param string $query The question
147     * @param int $limit The number of results to return
148     * @return Chunk[]
149     * @throws \Exception
150     */
151    public function getSimilarChunks($query, $limit = 4)
152    {
153        global $auth;
154        $vector = $this->openAI->getEmbedding($query);
155
156        $chunks = $this->storage->getSimilarChunks($vector, $limit);
157        $result = [];
158        foreach ($chunks as $chunk) {
159            // filter out chunks the user is not allowed to read
160            if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue;
161            $result[] = $chunk;
162            if (count($result) >= $limit) break;
163        }
164        return $result;
165    }
166
167
168    /**
169     * @param $text
170     * @return array
171     * @throws \Exception
172     * @todo maybe add overlap support
173     * @todo support splitting too long sentences
174     */
175    public function splitIntoChunks($text)
176    {
177        $sentenceSplitter = new Sentence();
178        $tiktok = new Encoder();
179
180        $chunks = [];
181        $sentences = $sentenceSplitter->split($text);
182
183        $chunklen = 0;
184        $chunk = '';
185        while ($sentence = array_shift($sentences)) {
186            $slen = count($tiktok->encode($sentence));
187            if ($slen > self::MAX_TOKEN_LEN) {
188                // sentence is too long, we need to split it further
189                if ($this->logger) $this->logger->warning('Sentence too long, splitting not implemented yet');
190                continue;
191            }
192
193            if ($chunklen + $slen < self::MAX_TOKEN_LEN) {
194                // add to current chunk
195                $chunk .= $sentence;
196                $chunklen += $slen;
197            } else {
198                // start new chunk
199                $chunks[] = $chunk;
200                $chunk = $sentence;
201                $chunklen = $slen;
202            }
203        }
204        $chunks[] = $chunk;
205
206        return $chunks;
207    }
208}
209