xref: /plugin/aichat/Embeddings.php (revision ed47fd87135eb149e159ef170f0ca8a6c136c9cc)
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{
2368908844SAndreas Gohr    /** @var int maximum overlap between chunks in tokens */
2430b9cbc7Ssplitbrain    final public const MAX_OVERLAP_LEN = 200;
258817535bSAndreas Gohr
26294a9eafSAndreas Gohr    /** @var ChatInterface */
276a18e0f4SAndreas Gohr    protected $chatModel;
286a18e0f4SAndreas Gohr
29294a9eafSAndreas Gohr    /** @var EmbeddingInterface */
306a18e0f4SAndreas Gohr    protected $embedModel;
316a18e0f4SAndreas Gohr
322ecc089aSAndreas Gohr    /** @var CLI|null */
332ecc089aSAndreas Gohr    protected $logger;
3468908844SAndreas Gohr    /** @var Encoder */
3568908844SAndreas Gohr    protected $tokenEncoder;
368817535bSAndreas Gohr
377ee8b02dSAndreas Gohr    /** @var AbstractStorage */
387ee8b02dSAndreas Gohr    protected $storage;
397ee8b02dSAndreas Gohr
4068908844SAndreas Gohr    /** @var array remember sentences when chunking */
4168908844SAndreas Gohr    private $sentenceQueue = [];
4268908844SAndreas Gohr
43c2b7a1f7SAndreas Gohr    /** @var int the time spent for the last similar chunk retrieval */
44c2b7a1f7SAndreas Gohr    public $timeSpent = 0;
45c2b7a1f7SAndreas Gohr
4634a1c478SAndreas Gohr    protected $configChunkSize;
4734a1c478SAndreas Gohr    protected $configContextChunks;
48720bb43fSAndreas Gohr    protected $similarityThreshold;
4934a1c478SAndreas Gohr
5034a1c478SAndreas Gohr    /**
5134a1c478SAndreas Gohr     * Embeddings constructor.
5234a1c478SAndreas Gohr     *
5334a1c478SAndreas Gohr     * @param ChatInterface $chatModel
5434a1c478SAndreas Gohr     * @param EmbeddingInterface $embedModel
5534a1c478SAndreas Gohr     * @param AbstractStorage $storage
5634a1c478SAndreas Gohr     * @param array $config The plugin configuration
5734a1c478SAndreas Gohr     */
586a18e0f4SAndreas Gohr    public function __construct(
59294a9eafSAndreas Gohr        ChatInterface      $chatModel,
60294a9eafSAndreas Gohr        EmbeddingInterface $embedModel,
6134a1c478SAndreas Gohr        AbstractStorage    $storage,
6234a1c478SAndreas Gohr                           $config
63aa6bbe75SAndreas Gohr    )
64aa6bbe75SAndreas Gohr    {
656a18e0f4SAndreas Gohr        $this->chatModel = $chatModel;
666a18e0f4SAndreas Gohr        $this->embedModel = $embedModel;
67f6ef2e50SAndreas Gohr        $this->storage = $storage;
6834a1c478SAndreas Gohr        $this->configChunkSize = $config['chunkSize'];
6934a1c478SAndreas Gohr        $this->configContextChunks = $config['contextChunks'];
70720bb43fSAndreas Gohr        $this->similarityThreshold = $config['similarityThreshold'] / 100;
717ee8b02dSAndreas Gohr    }
727ee8b02dSAndreas Gohr
737ee8b02dSAndreas Gohr    /**
747ee8b02dSAndreas Gohr     * Access storage
757ee8b02dSAndreas Gohr     *
767ee8b02dSAndreas Gohr     * @return AbstractStorage
777ee8b02dSAndreas Gohr     */
787ee8b02dSAndreas Gohr    public function getStorage()
797ee8b02dSAndreas Gohr    {
807ee8b02dSAndreas Gohr        return $this->storage;
812ecc089aSAndreas Gohr    }
822ecc089aSAndreas Gohr
832ecc089aSAndreas Gohr    /**
84aa6bbe75SAndreas Gohr     * Override the number of used context chunks
85aa6bbe75SAndreas Gohr     *
86aa6bbe75SAndreas Gohr     * @param int $max
87aa6bbe75SAndreas Gohr     * @return void
88aa6bbe75SAndreas Gohr     */
89aa6bbe75SAndreas Gohr    public function setConfigContextChunks(int $max)
90aa6bbe75SAndreas Gohr    {
91aa6bbe75SAndreas Gohr        if ($max <= 0) throw new \InvalidArgumentException('max context chunks must be greater than 0');
92aa6bbe75SAndreas Gohr        $this->configContextChunks = $max;
93aa6bbe75SAndreas Gohr    }
94aa6bbe75SAndreas Gohr
95aa6bbe75SAndreas Gohr    /**
96aa6bbe75SAndreas Gohr     * Override the similiarity threshold
97aa6bbe75SAndreas Gohr     *
98aa6bbe75SAndreas Gohr     * @param float $threshold
99aa6bbe75SAndreas Gohr     * @return void
100aa6bbe75SAndreas Gohr     */
101aa6bbe75SAndreas Gohr    public function setSimilarityThreshold(float $threshold)
102aa6bbe75SAndreas Gohr    {
103aa6bbe75SAndreas Gohr        if ($threshold < 0 || $threshold > 1) throw new \InvalidArgumentException('threshold must be between 0 and 1');
104aa6bbe75SAndreas Gohr        $this->similarityThreshold = $threshold;
105aa6bbe75SAndreas Gohr    }
106aa6bbe75SAndreas Gohr
107aa6bbe75SAndreas Gohr    /**
1082ecc089aSAndreas Gohr     * Add a logger instance
1092ecc089aSAndreas Gohr     *
1102ecc089aSAndreas Gohr     * @return void
1112ecc089aSAndreas Gohr     */
1122ecc089aSAndreas Gohr    public function setLogger(CLI $logger)
1132ecc089aSAndreas Gohr    {
1148817535bSAndreas Gohr        $this->logger = $logger;
1158817535bSAndreas Gohr    }
1168817535bSAndreas Gohr
1172ecc089aSAndreas Gohr    /**
11868908844SAndreas Gohr     * Get the token encoder instance
11968908844SAndreas Gohr     *
12068908844SAndreas Gohr     * @return Encoder
12168908844SAndreas Gohr     */
12268908844SAndreas Gohr    public function getTokenEncoder()
12368908844SAndreas Gohr    {
1247ebc7895Ssplitbrain        if (!$this->tokenEncoder instanceof Encoder) {
12568908844SAndreas Gohr            $this->tokenEncoder = new Encoder();
12668908844SAndreas Gohr        }
12768908844SAndreas Gohr        return $this->tokenEncoder;
12868908844SAndreas Gohr    }
12968908844SAndreas Gohr
13068908844SAndreas Gohr    /**
1316a18e0f4SAndreas Gohr     * Return the chunk size to use
1326a18e0f4SAndreas Gohr     *
1336a18e0f4SAndreas Gohr     * @return int
1346a18e0f4SAndreas Gohr     */
1356a18e0f4SAndreas Gohr    public function getChunkSize()
1366a18e0f4SAndreas Gohr    {
1376a18e0f4SAndreas Gohr        return min(
13834a1c478SAndreas Gohr            floor($this->chatModel->getMaxInputTokenLength() / 4), // be able to fit 4 chunks into the max input
13934a1c478SAndreas Gohr            floor($this->embedModel->getMaxInputTokenLength() * 0.9), // only use 90% of the embedding model to be safe
14034a1c478SAndreas Gohr            $this->configChunkSize, // this is usually the smallest
1416a18e0f4SAndreas Gohr        );
1426a18e0f4SAndreas Gohr    }
1436a18e0f4SAndreas Gohr
1446a18e0f4SAndreas Gohr    /**
1455284515dSAndreas Gohr     * Update the embeddings storage
1462ecc089aSAndreas Gohr     *
147ad38c5fdSAndreas Gohr     * @param string $skipRE Regular expression to filter out pages (full RE with delimiters)
148d5c102b3SAndreas Gohr     * @param string $matchRE Regular expression pages have to match to be included (full RE with delimiters)
1495284515dSAndreas Gohr     * @param bool $clear Should any existing storage be cleared before updating?
1502ecc089aSAndreas Gohr     * @return void
1515284515dSAndreas Gohr     * @throws \Exception
1522ecc089aSAndreas Gohr     */
153d5c102b3SAndreas Gohr    public function createNewIndex($skipRE = '', $matchRE = '', $clear = false)
1548817535bSAndreas Gohr    {
1558817535bSAndreas Gohr        $indexer = new Indexer();
1568817535bSAndreas Gohr        $pages = $indexer->getPages();
1578817535bSAndreas Gohr
158f6ef2e50SAndreas Gohr        $this->storage->startCreation($clear);
1595aa45b4dSAndreas Gohr        foreach ($pages as $pid => $page) {
1605aa45b4dSAndreas Gohr            $chunkID = $pid * 100; // chunk IDs start at page ID * 100
1615aa45b4dSAndreas Gohr
1625284515dSAndreas Gohr            if (
1635284515dSAndreas Gohr                !page_exists($page) ||
1645284515dSAndreas Gohr                isHiddenPage($page) ||
1654e206c13SAndreas Gohr                filesize(wikiFN($page)) < 150 || // skip very small pages
166d5c102b3SAndreas Gohr                ($skipRE && preg_match($skipRE, (string)$page)) ||
167d5c102b3SAndreas Gohr                ($matchRE && !preg_match($matchRE, ":$page"))
1685284515dSAndreas Gohr            ) {
1695284515dSAndreas Gohr                // this page should not be in the index (anymore)
1705284515dSAndreas Gohr                $this->storage->deletePageChunks($page, $chunkID);
1715284515dSAndreas Gohr                continue;
1725284515dSAndreas Gohr            }
1735284515dSAndreas Gohr
1747ee8b02dSAndreas Gohr            $firstChunk = $this->storage->getChunk($chunkID);
1757ee8b02dSAndreas Gohr            if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) {
1765aa45b4dSAndreas Gohr                // page is older than the chunks we have, reuse the existing chunks
1777ee8b02dSAndreas Gohr                $this->storage->reusePageChunks($page, $chunkID);
1787ebc7895Ssplitbrain                if ($this->logger instanceof CLI) $this->logger->info("Reusing chunks for $page");
1795aa45b4dSAndreas Gohr            } else {
1805aa45b4dSAndreas Gohr                // page is newer than the chunks we have, create new chunks
1817ee8b02dSAndreas Gohr                $this->storage->deletePageChunks($page, $chunkID);
182ecb0a423SAndreas Gohr                $chunks = $this->createPageChunks($page, $chunkID);
183ecb0a423SAndreas Gohr                if ($chunks) $this->storage->addPageChunks($chunks);
1845aa45b4dSAndreas Gohr            }
1855aa45b4dSAndreas Gohr        }
1867ee8b02dSAndreas Gohr        $this->storage->finalizeCreation();
1875aa45b4dSAndreas Gohr    }
1885aa45b4dSAndreas Gohr
1895aa45b4dSAndreas Gohr    /**
1907ee8b02dSAndreas Gohr     * Split the given page, fetch embedding vectors and return Chunks
1915aa45b4dSAndreas Gohr     *
19288305719SAndreas Gohr     * Will use the text renderer plugin if available to get the rendered text.
19388305719SAndreas Gohr     * Otherwise the raw wiki text is used.
19488305719SAndreas Gohr     *
1955aa45b4dSAndreas Gohr     * @param string $page Name of the page to split
1967ee8b02dSAndreas Gohr     * @param int $firstChunkID The ID of the first chunk of this page
1977ee8b02dSAndreas Gohr     * @return Chunk[] A list of chunks created for this page
198ab1f8ddeSAndreas Gohr     * @emits INDEXER_PAGE_ADD support plugins that add additional data to the page
1995aa45b4dSAndreas Gohr     * @throws \Exception
2005aa45b4dSAndreas Gohr     */
201ab1f8ddeSAndreas Gohr    public function createPageChunks($page, $firstChunkID)
2025aa45b4dSAndreas Gohr    {
2037ee8b02dSAndreas Gohr        $chunkList = [];
20488305719SAndreas Gohr
20588305719SAndreas Gohr        global $ID;
20688305719SAndreas Gohr        $ID = $page;
207303d0c59SAndreas Gohr        try {
208661701eeSAndreas Gohr            $text = p_cached_output(wikiFN($page), 'aichat', $page);
209303d0c59SAndreas Gohr        } catch (\Throwable $e) {
210303d0c59SAndreas Gohr            if ($this->logger) $this->logger->error(
211661701eeSAndreas Gohr                'Failed to render page {page}. Using raw text instead. {msg}',
212303d0c59SAndreas Gohr                ['page' => $page, 'msg' => $e->getMessage()]
213303d0c59SAndreas Gohr            );
214303d0c59SAndreas Gohr            $text = rawWiki($page);
215303d0c59SAndreas Gohr        }
216661701eeSAndreas Gohr
217661701eeSAndreas Gohr        $crumbs = $this->breadcrumbTrail($page);
21888305719SAndreas Gohr
219ab1f8ddeSAndreas Gohr        // allow plugins to modify the text before splitting
220ab1f8ddeSAndreas Gohr        $eventData = [
221ab1f8ddeSAndreas Gohr            'page' => $page,
222ab1f8ddeSAndreas Gohr            'body' => '',
223ab1f8ddeSAndreas Gohr            'metadata' => ['title' => $page, 'relation_references' => []],
224ab1f8ddeSAndreas Gohr        ];
225ab1f8ddeSAndreas Gohr        $event = new Event('INDEXER_PAGE_ADD', $eventData);
226ab1f8ddeSAndreas Gohr        if ($event->advise_before()) {
227ab1f8ddeSAndreas Gohr            $text = $eventData['body'] . ' ' . $text;
228ab1f8ddeSAndreas Gohr        } else {
229ab1f8ddeSAndreas Gohr            $text = $eventData['body'];
230ab1f8ddeSAndreas Gohr        }
231ab1f8ddeSAndreas Gohr
23288305719SAndreas Gohr        $parts = $this->splitIntoChunks($text);
2337ee8b02dSAndreas Gohr        foreach ($parts as $part) {
23430b9cbc7Ssplitbrain            if (trim((string)$part) == '') continue; // skip empty chunks
23593c1dbf4SAndreas Gohr
236661701eeSAndreas Gohr            $part = $crumbs . "\n\n" . $part; // add breadcrumbs to each chunk
237661701eeSAndreas Gohr
238ad38c5fdSAndreas Gohr            try {
2396a18e0f4SAndreas Gohr                $embedding = $this->embedModel->getEmbedding($part);
240ad38c5fdSAndreas Gohr            } catch (\Exception $e) {
2417ebc7895Ssplitbrain                if ($this->logger instanceof CLI) {
242ad38c5fdSAndreas Gohr                    $this->logger->error(
243ad38c5fdSAndreas Gohr                        'Failed to get embedding for chunk of page {page}: {msg}',
244ad38c5fdSAndreas Gohr                        ['page' => $page, 'msg' => $e->getMessage()]
245ad38c5fdSAndreas Gohr                    );
246ad38c5fdSAndreas Gohr                }
247ad38c5fdSAndreas Gohr                continue;
248ad38c5fdSAndreas Gohr            }
2497ee8b02dSAndreas Gohr            $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding);
2507ee8b02dSAndreas Gohr            $firstChunkID++;
2518817535bSAndreas Gohr        }
2527ebc7895Ssplitbrain        if ($this->logger instanceof CLI) {
2537ebc7895Ssplitbrain            if ($chunkList !== []) {
254f8d5ae01SAndreas Gohr                $this->logger->success(
255f8d5ae01SAndreas Gohr                    '{id} split into {count} chunks',
256f8d5ae01SAndreas Gohr                    ['id' => $page, 'count' => count($chunkList)]
257f8d5ae01SAndreas Gohr                );
25893c1dbf4SAndreas Gohr            } else {
25993c1dbf4SAndreas Gohr                $this->logger->warning('{id} could not be split into chunks', ['id' => $page]);
26093c1dbf4SAndreas Gohr            }
2618817535bSAndreas Gohr        }
2627ee8b02dSAndreas Gohr        return $chunkList;
2638817535bSAndreas Gohr    }
2648817535bSAndreas Gohr
2659e81bea7SAndreas Gohr    /**
2669e81bea7SAndreas Gohr     * Do a nearest neighbor search for chunks similar to the given question
2679e81bea7SAndreas Gohr     *
2689e81bea7SAndreas Gohr     * Returns only chunks the current user is allowed to read, may return an empty result.
26968908844SAndreas Gohr     * The number of returned chunks depends on the MAX_CONTEXT_LEN setting.
2709e81bea7SAndreas Gohr     *
2719e81bea7SAndreas Gohr     * @param string $query The question
272e33a1d7aSAndreas Gohr     * @param string $lang Limit results to this language
273aa6bbe75SAndreas Gohr     * @param bool $limits Apply chat token limits to the number of chunks returned?
2747ee8b02dSAndreas Gohr     * @return Chunk[]
2759e81bea7SAndreas Gohr     * @throws \Exception
2769e81bea7SAndreas Gohr     */
277aa6bbe75SAndreas Gohr    public function getSimilarChunks($query, $lang = '', $limits = true)
2788817535bSAndreas Gohr    {
2799e81bea7SAndreas Gohr        global $auth;
2806a18e0f4SAndreas Gohr        $vector = $this->embedModel->getEmbedding($query);
2818817535bSAndreas Gohr
282aa6bbe75SAndreas Gohr        if ($limits) {
283e3640be8SAndreas Gohr            $fetch = min(
28434a1c478SAndreas Gohr                ($this->chatModel->getMaxInputTokenLength() / $this->getChunkSize()),
28534a1c478SAndreas Gohr                $this->configContextChunks
286f6ef2e50SAndreas Gohr            );
287aa6bbe75SAndreas Gohr        } else {
288aa6bbe75SAndreas Gohr            $fetch = $this->configContextChunks;
289aa6bbe75SAndreas Gohr        }
290aee9b383SAndreas Gohr
291aee9b383SAndreas Gohr        $time = microtime(true);
292e33a1d7aSAndreas Gohr        $chunks = $this->storage->getSimilarChunks($vector, $lang, $fetch);
2935f71c9bbSAndreas Gohr        $this->timeSpent = round(microtime(true) - $time, 2);
2947ebc7895Ssplitbrain        if ($this->logger instanceof CLI) {
295aee9b383SAndreas Gohr            $this->logger->info(
296c2f55081SAndreas Gohr                'Fetched {count} similar chunks from store in {time} seconds. Query: {query}',
297c2f55081SAndreas Gohr                ['count' => count($chunks), 'time' => $this->timeSpent, 'query' => $query]
298aee9b383SAndreas Gohr            );
299aee9b383SAndreas Gohr        }
30068908844SAndreas Gohr
30168908844SAndreas Gohr        $size = 0;
3028817535bSAndreas Gohr        $result = [];
3037ee8b02dSAndreas Gohr        foreach ($chunks as $chunk) {
3049e81bea7SAndreas Gohr            // filter out chunks the user is not allowed to read
3057ee8b02dSAndreas Gohr            if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue;
306720bb43fSAndreas Gohr            if ($chunk->getScore() < $this->similarityThreshold) continue;
30768908844SAndreas Gohr
308aa6bbe75SAndreas Gohr            if ($limits) {
30968908844SAndreas Gohr                $chunkSize = count($this->getTokenEncoder()->encode($chunk->getText()));
31034a1c478SAndreas Gohr                if ($size + $chunkSize > $this->chatModel->getMaxInputTokenLength()) break; // we have enough
311aa6bbe75SAndreas Gohr            }
31268908844SAndreas Gohr
3139e81bea7SAndreas Gohr            $result[] = $chunk;
314aa6bbe75SAndreas Gohr            $size += $chunkSize ?? 0;
315aa6bbe75SAndreas Gohr
316aa6bbe75SAndreas Gohr            if (count($result) >= $this->configContextChunks) break; // we have enough
3178817535bSAndreas Gohr        }
3188817535bSAndreas Gohr        return $result;
3198817535bSAndreas Gohr    }
3208817535bSAndreas Gohr
321661701eeSAndreas Gohr    /**
322*ed47fd87SAndreas Gohr     * Returns all chunks for a page
323*ed47fd87SAndreas Gohr     *
324*ed47fd87SAndreas Gohr     * Does not apply configContextChunks but checks token limits if requested
325*ed47fd87SAndreas Gohr     *
326*ed47fd87SAndreas Gohr     * @param string $page
327*ed47fd87SAndreas Gohr     * @param bool $limits Apply chat token limits to the number of chunks returned?
328*ed47fd87SAndreas Gohr     * @return Chunk[]
329*ed47fd87SAndreas Gohr     */
330*ed47fd87SAndreas Gohr    public function getPageChunks($page, $limits = true)
331*ed47fd87SAndreas Gohr    {
332*ed47fd87SAndreas Gohr        global $auth;
333*ed47fd87SAndreas Gohr        if ($auth && auth_quickaclcheck($page) < AUTH_READ) {
334*ed47fd87SAndreas Gohr            if ($this->logger instanceof CLI) $this->logger->warning(
335*ed47fd87SAndreas Gohr                'User not allowed to read context page {page}', ['page' => $page]
336*ed47fd87SAndreas Gohr            );
337*ed47fd87SAndreas Gohr            return [];
338*ed47fd87SAndreas Gohr        }
339*ed47fd87SAndreas Gohr
340*ed47fd87SAndreas Gohr        $indexer = new Indexer();
341*ed47fd87SAndreas Gohr        $pages = $indexer->getPages();
342*ed47fd87SAndreas Gohr        $pos = array_search(cleanID($page), $pages);
343*ed47fd87SAndreas Gohr
344*ed47fd87SAndreas Gohr        if ($pos === false) {
345*ed47fd87SAndreas Gohr            if ($this->logger instanceof CLI) $this->logger->warning(
346*ed47fd87SAndreas Gohr                'Context page {page} is not in index', ['page' => $page]
347*ed47fd87SAndreas Gohr            );
348*ed47fd87SAndreas Gohr            return [];
349*ed47fd87SAndreas Gohr        }
350*ed47fd87SAndreas Gohr
351*ed47fd87SAndreas Gohr        $chunks = $this->storage->getPageChunks($page, $pos * 100);
352*ed47fd87SAndreas Gohr
353*ed47fd87SAndreas Gohr        $size = 0;
354*ed47fd87SAndreas Gohr        $result = [];
355*ed47fd87SAndreas Gohr        foreach ($chunks as $chunk) {
356*ed47fd87SAndreas Gohr            if ($limits) {
357*ed47fd87SAndreas Gohr                $chunkSize = count($this->getTokenEncoder()->encode($chunk->getText()));
358*ed47fd87SAndreas Gohr                if ($size + $chunkSize > $this->chatModel->getMaxInputTokenLength()) break; // we have enough
359*ed47fd87SAndreas Gohr            }
360*ed47fd87SAndreas Gohr
361*ed47fd87SAndreas Gohr            $result[] = $chunk;
362*ed47fd87SAndreas Gohr            $size += $chunkSize ?? 0;
363*ed47fd87SAndreas Gohr        }
364*ed47fd87SAndreas Gohr
365*ed47fd87SAndreas Gohr        return $result;
366*ed47fd87SAndreas Gohr    }
367*ed47fd87SAndreas Gohr
368*ed47fd87SAndreas Gohr
369*ed47fd87SAndreas Gohr    /**
370661701eeSAndreas Gohr     * Create a breadcrumb trail for the given page
371661701eeSAndreas Gohr     *
372661701eeSAndreas Gohr     * Uses the first heading of each namespace and the page itself. This is added as a prefix to
373661701eeSAndreas Gohr     * each chunk to give the AI some context.
374661701eeSAndreas Gohr     *
375661701eeSAndreas Gohr     * @param string $id
376661701eeSAndreas Gohr     * @return string
377661701eeSAndreas Gohr     */
378661701eeSAndreas Gohr    protected function breadcrumbTrail($id)
379661701eeSAndreas Gohr    {
380661701eeSAndreas Gohr        $namespaces = explode(':', getNS($id));
381661701eeSAndreas Gohr        $resolver = new PageResolver($id);
382661701eeSAndreas Gohr        $crumbs = [];
383661701eeSAndreas Gohr
384661701eeSAndreas Gohr        // all namespaces
385661701eeSAndreas Gohr        $check = '';
386661701eeSAndreas Gohr        foreach ($namespaces as $namespace) {
387661701eeSAndreas Gohr            $check .= $namespace . ':';
388661701eeSAndreas Gohr            $page = $resolver->resolveId($check);
389661701eeSAndreas Gohr            $title = p_get_first_heading($page);
390661701eeSAndreas Gohr            $crumbs[] = $title ? "$title ($namespace)" : $namespace;
391661701eeSAndreas Gohr        }
392661701eeSAndreas Gohr
393661701eeSAndreas Gohr        // the page itself
394661701eeSAndreas Gohr        $title = p_get_first_heading($id);
395661701eeSAndreas Gohr        $page = noNS($id);
396661701eeSAndreas Gohr        $crumbs[] = $title ? "$title ($page)" : $page;
397661701eeSAndreas Gohr
398661701eeSAndreas Gohr        return implode(' » ', $crumbs);
399661701eeSAndreas Gohr    }
4005786be46SAndreas Gohr
4015786be46SAndreas Gohr    /**
4028817535bSAndreas Gohr     * @param $text
4038817535bSAndreas Gohr     * @return array
4048817535bSAndreas Gohr     * @throws \Exception
4058817535bSAndreas Gohr     * @todo support splitting too long sentences
4068817535bSAndreas Gohr     */
407ab1f8ddeSAndreas Gohr    protected function splitIntoChunks($text)
4088817535bSAndreas Gohr    {
4098817535bSAndreas Gohr        $sentenceSplitter = new Sentence();
41068908844SAndreas Gohr        $tiktok = $this->getTokenEncoder();
4118817535bSAndreas Gohr
4128817535bSAndreas Gohr        $chunks = [];
4138817535bSAndreas Gohr        $sentences = $sentenceSplitter->split($text);
4148817535bSAndreas Gohr
4158817535bSAndreas Gohr        $chunklen = 0;
4168817535bSAndreas Gohr        $chunk = '';
4178817535bSAndreas Gohr        while ($sentence = array_shift($sentences)) {
4188817535bSAndreas Gohr            $slen = count($tiktok->encode($sentence));
4196a18e0f4SAndreas Gohr            if ($slen > $this->getChunkSize()) {
4208817535bSAndreas Gohr                // sentence is too long, we need to split it further
421f8d5ae01SAndreas Gohr                if ($this->logger instanceof CLI) $this->logger->warning(
422f8d5ae01SAndreas Gohr                    'Sentence too long, splitting not implemented yet'
423f8d5ae01SAndreas Gohr                );
424ad38c5fdSAndreas Gohr                continue;
4258817535bSAndreas Gohr            }
4268817535bSAndreas Gohr
4276a18e0f4SAndreas Gohr            if ($chunklen + $slen < $this->getChunkSize()) {
4288817535bSAndreas Gohr                // add to current chunk
4298817535bSAndreas Gohr                $chunk .= $sentence;
4308817535bSAndreas Gohr                $chunklen += $slen;
43168908844SAndreas Gohr                // remember sentence for overlap check
43268908844SAndreas Gohr                $this->rememberSentence($sentence);
4338817535bSAndreas Gohr            } else {
43468908844SAndreas Gohr                // add current chunk to result
435ab1f8ddeSAndreas Gohr                $chunk = trim($chunk);
436ab1f8ddeSAndreas Gohr                if ($chunk !== '') $chunks[] = $chunk;
43768908844SAndreas Gohr
43868908844SAndreas Gohr                // start new chunk with remembered sentences
4397ebc7895Ssplitbrain                $chunk = implode(' ', $this->sentenceQueue);
44068908844SAndreas Gohr                $chunk .= $sentence;
44168908844SAndreas Gohr                $chunklen = count($tiktok->encode($chunk));
4428817535bSAndreas Gohr            }
4438817535bSAndreas Gohr        }
4448817535bSAndreas Gohr        $chunks[] = $chunk;
4458817535bSAndreas Gohr
4468817535bSAndreas Gohr        return $chunks;
4478817535bSAndreas Gohr    }
44868908844SAndreas Gohr
44968908844SAndreas Gohr    /**
45068908844SAndreas Gohr     * Add a sentence to the queue of remembered sentences
45168908844SAndreas Gohr     *
45268908844SAndreas Gohr     * @param string $sentence
45368908844SAndreas Gohr     * @return void
45468908844SAndreas Gohr     */
45568908844SAndreas Gohr    protected function rememberSentence($sentence)
45668908844SAndreas Gohr    {
45768908844SAndreas Gohr        // add sentence to queue
45868908844SAndreas Gohr        $this->sentenceQueue[] = $sentence;
45968908844SAndreas Gohr
46068908844SAndreas Gohr        // remove oldest sentences from queue until we are below the max overlap
46168908844SAndreas Gohr        $encoder = $this->getTokenEncoder();
4627ebc7895Ssplitbrain        while (count($encoder->encode(implode(' ', $this->sentenceQueue))) > self::MAX_OVERLAP_LEN) {
46368908844SAndreas Gohr            array_shift($this->sentenceQueue);
46468908844SAndreas Gohr        }
46568908844SAndreas Gohr    }
4668817535bSAndreas Gohr}
467