xref: /plugin/aichat/Storage/SQLiteStorage.php (revision 8285fff93bda4602771c807cbe9218d1f3b88d32)
13379af09SAndreas Gohr<?php /** @noinspection SqlResolve */
2f6ef2e50SAndreas Gohr
3f6ef2e50SAndreas Gohrnamespace dokuwiki\plugin\aichat\Storage;
4f6ef2e50SAndreas Gohr
5f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Chunk;
6f6ef2e50SAndreas Gohruse dokuwiki\plugin\sqlite\SQLiteDB;
73379af09SAndreas Gohruse KMeans\Cluster;
83379af09SAndreas Gohruse KMeans\Point;
93379af09SAndreas Gohruse KMeans\Space;
10f6ef2e50SAndreas Gohr
11f6ef2e50SAndreas Gohr/**
12f6ef2e50SAndreas Gohr * Implements the storage backend using a SQLite database
1335555bacSAndreas Gohr *
1435555bacSAndreas Gohr * Note: all embeddings are stored and returned as normalized vectors
15f6ef2e50SAndreas Gohr */
16f6ef2e50SAndreas Gohrclass SQLiteStorage extends AbstractStorage
17f6ef2e50SAndreas Gohr{
1881b450c8SAndreas Gohr    /** @var float minimum similarity to consider a chunk a match */
1981b450c8SAndreas Gohr    const SIMILARITY_THRESHOLD = 0.75;
2081b450c8SAndreas Gohr
213379af09SAndreas Gohr    /** @var int Number of documents to randomly sample to create the clusters */
223379af09SAndreas Gohr    const SAMPLE_SIZE = 2000;
233379af09SAndreas Gohr    /** @var int The average size of each cluster */
243379af09SAndreas Gohr    const CLUSTER_SIZE = 400;
253379af09SAndreas Gohr
26f6ef2e50SAndreas Gohr    /** @var SQLiteDB */
27f6ef2e50SAndreas Gohr    protected $db;
28f6ef2e50SAndreas Gohr
29f6ef2e50SAndreas Gohr    /**
30f6ef2e50SAndreas Gohr     * Initializes the database connection and registers our custom function
31f6ef2e50SAndreas Gohr     *
32f6ef2e50SAndreas Gohr     * @throws \Exception
33f6ef2e50SAndreas Gohr     */
34f6ef2e50SAndreas Gohr    public function __construct()
35f6ef2e50SAndreas Gohr    {
36f6ef2e50SAndreas Gohr        $this->db = new SQLiteDB('aichat', DOKU_PLUGIN . 'aichat/db/');
37f6ef2e50SAndreas Gohr        $this->db->getPdo()->sqliteCreateFunction('COSIM', [$this, 'sqliteCosineSimilarityCallback'], 2);
38f6ef2e50SAndreas Gohr    }
39f6ef2e50SAndreas Gohr
40f6ef2e50SAndreas Gohr    /** @inheritdoc */
41f6ef2e50SAndreas Gohr    public function getChunk($chunkID)
42f6ef2e50SAndreas Gohr    {
43f6ef2e50SAndreas Gohr        $record = $this->db->queryRecord('SELECT * FROM embeddings WHERE id = ?', [$chunkID]);
44f6ef2e50SAndreas Gohr        if (!$record) return null;
45f6ef2e50SAndreas Gohr
46f6ef2e50SAndreas Gohr        return new Chunk(
47f6ef2e50SAndreas Gohr            $record['page'],
48f6ef2e50SAndreas Gohr            $record['id'],
49f6ef2e50SAndreas Gohr            $record['chunk'],
50f6ef2e50SAndreas Gohr            json_decode($record['embedding'], true),
51f6ef2e50SAndreas Gohr            $record['created']
52f6ef2e50SAndreas Gohr        );
53f6ef2e50SAndreas Gohr    }
54f6ef2e50SAndreas Gohr
55f6ef2e50SAndreas Gohr    /** @inheritdoc */
56f6ef2e50SAndreas Gohr    public function startCreation($clear = false)
57f6ef2e50SAndreas Gohr    {
58f6ef2e50SAndreas Gohr        if ($clear) {
59f6ef2e50SAndreas Gohr            /** @noinspection SqlWithoutWhere */
60f6ef2e50SAndreas Gohr            $this->db->exec('DELETE FROM embeddings');
61f6ef2e50SAndreas Gohr        }
62f6ef2e50SAndreas Gohr    }
63f6ef2e50SAndreas Gohr
64f6ef2e50SAndreas Gohr    /** @inheritdoc */
65f6ef2e50SAndreas Gohr    public function reusePageChunks($page, $firstChunkID)
66f6ef2e50SAndreas Gohr    {
67f6ef2e50SAndreas Gohr        // no-op
68f6ef2e50SAndreas Gohr    }
69f6ef2e50SAndreas Gohr
70f6ef2e50SAndreas Gohr    /** @inheritdoc */
71f6ef2e50SAndreas Gohr    public function deletePageChunks($page, $firstChunkID)
72f6ef2e50SAndreas Gohr    {
73f6ef2e50SAndreas Gohr        $this->db->exec('DELETE FROM embeddings WHERE page = ?', [$page]);
74f6ef2e50SAndreas Gohr    }
75f6ef2e50SAndreas Gohr
76f6ef2e50SAndreas Gohr    /** @inheritdoc */
77f6ef2e50SAndreas Gohr    public function addPageChunks($chunks)
78f6ef2e50SAndreas Gohr    {
79f6ef2e50SAndreas Gohr        foreach ($chunks as $chunk) {
80f6ef2e50SAndreas Gohr            $this->db->saveRecord('embeddings', [
81f6ef2e50SAndreas Gohr                'page' => $chunk->getPage(),
82f6ef2e50SAndreas Gohr                'id' => $chunk->getId(),
83f6ef2e50SAndreas Gohr                'chunk' => $chunk->getText(),
84f6ef2e50SAndreas Gohr                'embedding' => json_encode($chunk->getEmbedding()),
85f6ef2e50SAndreas Gohr                'created' => $chunk->getCreated()
86f6ef2e50SAndreas Gohr            ]);
87f6ef2e50SAndreas Gohr        }
88f6ef2e50SAndreas Gohr    }
89f6ef2e50SAndreas Gohr
90f6ef2e50SAndreas Gohr    /** @inheritdoc */
91f6ef2e50SAndreas Gohr    public function finalizeCreation()
92f6ef2e50SAndreas Gohr    {
933379af09SAndreas Gohr        if (!$this->hasClusters()) {
943379af09SAndreas Gohr            $this->createClusters();
953379af09SAndreas Gohr        }
963379af09SAndreas Gohr        $this->setChunkClusters();
973379af09SAndreas Gohr
98f6ef2e50SAndreas Gohr        $this->db->exec('VACUUM');
99f6ef2e50SAndreas Gohr    }
100f6ef2e50SAndreas Gohr
101f6ef2e50SAndreas Gohr    /** @inheritdoc */
1023379af09SAndreas Gohr    public function runMaintenance()
1033379af09SAndreas Gohr    {
1043379af09SAndreas Gohr        $this->createClusters();
1053379af09SAndreas Gohr        $this->setChunkClusters();
1063379af09SAndreas Gohr    }
1073379af09SAndreas Gohr
1083379af09SAndreas Gohr    /** @inheritdoc */
10901f06932SAndreas Gohr    public function getPageChunks($page, $firstChunkID)
11001f06932SAndreas Gohr    {
11101f06932SAndreas Gohr        $result = $this->db->queryAll(
11201f06932SAndreas Gohr            'SELECT * FROM embeddings WHERE page = ?',
11301f06932SAndreas Gohr            [$page]
11401f06932SAndreas Gohr        );
11501f06932SAndreas Gohr        $chunks = [];
11601f06932SAndreas Gohr        foreach ($result as $record) {
11701f06932SAndreas Gohr            $chunks[] = new Chunk(
11801f06932SAndreas Gohr                $record['page'],
11901f06932SAndreas Gohr                $record['id'],
12001f06932SAndreas Gohr                $record['chunk'],
12101f06932SAndreas Gohr                json_decode($record['embedding'], true),
12201f06932SAndreas Gohr                $record['created']
12301f06932SAndreas Gohr            );
12401f06932SAndreas Gohr        }
12501f06932SAndreas Gohr        return $chunks;
12601f06932SAndreas Gohr    }
12701f06932SAndreas Gohr
12801f06932SAndreas Gohr    /** @inheritdoc */
129f6ef2e50SAndreas Gohr    public function getSimilarChunks($vector, $limit = 4)
130f6ef2e50SAndreas Gohr    {
1313379af09SAndreas Gohr        $cluster = $this->getCluster($vector);
132*8285fff9SAndreas Gohr        if ($this->logger) $this->logger->info(
133*8285fff9SAndreas Gohr            'Using cluster {cluster} for similarity search', ['cluster' => $cluster]
134*8285fff9SAndreas Gohr        );
1353379af09SAndreas Gohr
136f6ef2e50SAndreas Gohr        $result = $this->db->queryAll(
137f6ef2e50SAndreas Gohr            'SELECT *, COSIM(?, embedding) AS similarity
138f6ef2e50SAndreas Gohr               FROM embeddings
1393379af09SAndreas Gohr              WHERE cluster = ?
1403379af09SAndreas Gohr                AND GETACCESSLEVEL(page) > 0
14181b450c8SAndreas Gohr                AND similarity > CAST(? AS FLOAT)
142f6ef2e50SAndreas Gohr           ORDER BY similarity DESC
143f6ef2e50SAndreas Gohr              LIMIT ?',
1443379af09SAndreas Gohr            [json_encode($vector), $cluster, self::SIMILARITY_THRESHOLD, $limit]
145f6ef2e50SAndreas Gohr        );
146f6ef2e50SAndreas Gohr        $chunks = [];
147f6ef2e50SAndreas Gohr        foreach ($result as $record) {
148f6ef2e50SAndreas Gohr            $chunks[] = new Chunk(
149f6ef2e50SAndreas Gohr                $record['page'],
150f6ef2e50SAndreas Gohr                $record['id'],
151f6ef2e50SAndreas Gohr                $record['chunk'],
152f6ef2e50SAndreas Gohr                json_decode($record['embedding'], true),
1539b3d1b36SAndreas Gohr                $record['created'],
1549b3d1b36SAndreas Gohr                $record['similarity']
155f6ef2e50SAndreas Gohr            );
156f6ef2e50SAndreas Gohr        }
157f6ef2e50SAndreas Gohr        return $chunks;
158f6ef2e50SAndreas Gohr    }
159f6ef2e50SAndreas Gohr
160f6ef2e50SAndreas Gohr    /** @inheritdoc */
161f6ef2e50SAndreas Gohr    public function statistics()
162f6ef2e50SAndreas Gohr    {
163f6ef2e50SAndreas Gohr        $items = $this->db->queryValue('SELECT COUNT(*) FROM embeddings');
164f6ef2e50SAndreas Gohr        $size = $this->db->queryValue(
165f6ef2e50SAndreas Gohr            'SELECT page_count * page_size as size FROM pragma_page_count(), pragma_page_size()'
166f6ef2e50SAndreas Gohr        );
1673379af09SAndreas Gohr        $query = "SELECT cluster, COUNT(*) || ' chunks' as cnt FROM embeddings GROUP BY cluster ORDER BY cluster";
1683379af09SAndreas Gohr        $clusters = $this->db->queryKeyValueList($query);
1693379af09SAndreas Gohr
170f6ef2e50SAndreas Gohr        return [
171f6ef2e50SAndreas Gohr            'storage type' => 'SQLite',
172f6ef2e50SAndreas Gohr            'chunks' => $items,
1733379af09SAndreas Gohr            'db size' => filesize_h($size),
1743379af09SAndreas Gohr            'clusters' => $clusters,
175f6ef2e50SAndreas Gohr        ];
176f6ef2e50SAndreas Gohr    }
177f6ef2e50SAndreas Gohr
178f6ef2e50SAndreas Gohr    /**
179f6ef2e50SAndreas Gohr     * Method registered as SQLite callback to calculate the cosine similarity
180f6ef2e50SAndreas Gohr     *
181f6ef2e50SAndreas Gohr     * @param string $query JSON encoded vector array
182f6ef2e50SAndreas Gohr     * @param string $embedding JSON encoded vector array
183f6ef2e50SAndreas Gohr     * @return float
184f6ef2e50SAndreas Gohr     */
185f6ef2e50SAndreas Gohr    public function sqliteCosineSimilarityCallback($query, $embedding)
186f6ef2e50SAndreas Gohr    {
187f6ef2e50SAndreas Gohr        return (float)$this->cosineSimilarity(json_decode($query), json_decode($embedding));
188f6ef2e50SAndreas Gohr    }
189f6ef2e50SAndreas Gohr
190f6ef2e50SAndreas Gohr    /**
191f6ef2e50SAndreas Gohr     * Calculate the cosine similarity between two vectors
192f6ef2e50SAndreas Gohr     *
19335555bacSAndreas Gohr     * Actually just calculating the dot product of the two vectors, since they are normalized
19435555bacSAndreas Gohr     *
19535555bacSAndreas Gohr     * @param float[] $queryVector The normalized vector of the search phrase
19635555bacSAndreas Gohr     * @param float[] $embedding The normalized vector of the chunk
197f6ef2e50SAndreas Gohr     * @return float
198f6ef2e50SAndreas Gohr     */
199f6ef2e50SAndreas Gohr    protected function cosineSimilarity($queryVector, $embedding)
200f6ef2e50SAndreas Gohr    {
201f6ef2e50SAndreas Gohr        $dotProduct = 0;
202f6ef2e50SAndreas Gohr        foreach ($queryVector as $key => $value) {
203f6ef2e50SAndreas Gohr            $dotProduct += $value * $embedding[$key];
204f6ef2e50SAndreas Gohr        }
20535555bacSAndreas Gohr        return $dotProduct;
206f6ef2e50SAndreas Gohr    }
2073379af09SAndreas Gohr
2083379af09SAndreas Gohr    /**
2093379af09SAndreas Gohr     * Create new clusters based on random chunks
2103379af09SAndreas Gohr     *
2113379af09SAndreas Gohr     * @noinspection SqlWithoutWhere
2123379af09SAndreas Gohr     */
2133379af09SAndreas Gohr    protected function createClusters()
2143379af09SAndreas Gohr    {
2153379af09SAndreas Gohr        if ($this->logger) $this->logger->info('Creating new clusters...');
2163379af09SAndreas Gohr        $this->db->getPdo()->beginTransaction();
2173379af09SAndreas Gohr        try {
2183379af09SAndreas Gohr            // clean up old cluster data
2193379af09SAndreas Gohr            $query = 'DELETE FROM clusters';
2203379af09SAndreas Gohr            $this->db->exec($query);
2213379af09SAndreas Gohr            $query = 'UPDATE embeddings SET cluster = NULL';
2223379af09SAndreas Gohr            $this->db->exec($query);
2233379af09SAndreas Gohr
2243379af09SAndreas Gohr            // get a random selection of chunks
2253379af09SAndreas Gohr            $query = 'SELECT id, embedding FROM embeddings ORDER BY RANDOM() LIMIT ?';
2263379af09SAndreas Gohr            $result = $this->db->queryAll($query, [self::SAMPLE_SIZE]);
2273379af09SAndreas Gohr            if (!$result) return; // no data to cluster
2283379af09SAndreas Gohr            $dimensions = count(json_decode($result[0]['embedding'], true));
2293379af09SAndreas Gohr
2303379af09SAndreas Gohr            // get the number of all chunks, to calculate the number of clusters
2313379af09SAndreas Gohr            $query = 'SELECT COUNT(*) FROM embeddings';
2323379af09SAndreas Gohr            $total = $this->db->queryValue($query);
2333379af09SAndreas Gohr            $clustercount = ceil($total / self::CLUSTER_SIZE);
2343379af09SAndreas Gohr            if ($this->logger) $this->logger->info('Creating {clusters} clusters', ['clusters' => $clustercount]);
2353379af09SAndreas Gohr
2363379af09SAndreas Gohr            // cluster them using kmeans
2373379af09SAndreas Gohr            $space = new Space($dimensions);
2383379af09SAndreas Gohr            foreach ($result as $record) {
2393379af09SAndreas Gohr                $space->addPoint(json_decode($record['embedding'], true));
2403379af09SAndreas Gohr            }
2413379af09SAndreas Gohr            $clusters = $space->solve($clustercount, function ($space, $clusters) {
2423379af09SAndreas Gohr                static $iterations = 0;
2433379af09SAndreas Gohr                ++$iterations;
2443379af09SAndreas Gohr                if ($this->logger) {
2453379af09SAndreas Gohr                    $clustercounts = join(',', array_map('count', $clusters));
2463379af09SAndreas Gohr                    $this->logger->info('Iteration {iteration}: [{clusters}]', [
2473379af09SAndreas Gohr                        'iteration' => $iterations, 'clusters' => $clustercounts
2483379af09SAndreas Gohr                    ]);
2493379af09SAndreas Gohr                }
2503379af09SAndreas Gohr            }, Cluster::INIT_KMEANS_PLUS_PLUS);
2513379af09SAndreas Gohr
2523379af09SAndreas Gohr            // store the clusters
2533379af09SAndreas Gohr            foreach ($clusters as $clusterID => $cluster) {
2543379af09SAndreas Gohr                /** @var Cluster $cluster */
2553379af09SAndreas Gohr                $centroid = $cluster->getCoordinates();
2563379af09SAndreas Gohr                $query = 'INSERT INTO clusters (cluster, centroid) VALUES (?, ?)';
2573379af09SAndreas Gohr                $this->db->exec($query, [$clusterID, json_encode($centroid)]);
2583379af09SAndreas Gohr            }
2593379af09SAndreas Gohr
2603379af09SAndreas Gohr            $this->db->getPdo()->commit();
2613379af09SAndreas Gohr            if ($this->logger) $this->logger->success('Created {clusters} clusters', ['clusters' => count($clusters)]);
2623379af09SAndreas Gohr        } catch (\Exception $e) {
2633379af09SAndreas Gohr            $this->db->getPdo()->rollBack();
2643379af09SAndreas Gohr            throw new \RuntimeException('Clustering failed', 0, $e);
2653379af09SAndreas Gohr        }
2663379af09SAndreas Gohr    }
2673379af09SAndreas Gohr
2683379af09SAndreas Gohr    /**
2693379af09SAndreas Gohr     * Assign the nearest cluster for all chunks that don't have one
2703379af09SAndreas Gohr     *
2713379af09SAndreas Gohr     * @return void
2723379af09SAndreas Gohr     */
2733379af09SAndreas Gohr    protected function setChunkClusters()
2743379af09SAndreas Gohr    {
2753379af09SAndreas Gohr        if ($this->logger) $this->logger->info('Assigning clusters to chunks...');
2763379af09SAndreas Gohr        $query = 'SELECT id, embedding FROM embeddings WHERE cluster IS NULL';
2773379af09SAndreas Gohr        $handle = $this->db->query($query);
2783379af09SAndreas Gohr
2793379af09SAndreas Gohr        while ($record = $handle->fetch(\PDO::FETCH_ASSOC)) {
2803379af09SAndreas Gohr            $vector = json_decode($record['embedding'], true);
2813379af09SAndreas Gohr            $cluster = $this->getCluster($vector);
2823379af09SAndreas Gohr            $query = 'UPDATE embeddings SET cluster = ? WHERE id = ?';
2833379af09SAndreas Gohr            $this->db->exec($query, [$cluster, $record['id']]);
2843379af09SAndreas Gohr            if ($this->logger) $this->logger->success(
2853379af09SAndreas Gohr                'Chunk {id} assigned to cluster {cluster}', ['id' => $record['id'], 'cluster' => $cluster]
2863379af09SAndreas Gohr            );
2873379af09SAndreas Gohr        }
2883379af09SAndreas Gohr        $handle->closeCursor();
2893379af09SAndreas Gohr    }
2903379af09SAndreas Gohr
2913379af09SAndreas Gohr    /**
2923379af09SAndreas Gohr     * Get the nearest cluster for the given vector
2933379af09SAndreas Gohr     *
2943379af09SAndreas Gohr     * @param float[] $vector
2953379af09SAndreas Gohr     * @return int|null
2963379af09SAndreas Gohr     */
2973379af09SAndreas Gohr    protected function getCluster($vector)
2983379af09SAndreas Gohr    {
2993379af09SAndreas Gohr        $query = 'SELECT cluster, centroid FROM clusters ORDER BY COSIM(centroid, ?) DESC LIMIT 1';
3003379af09SAndreas Gohr        $result = $this->db->queryRecord($query, [json_encode($vector)]);
3013379af09SAndreas Gohr        if (!$result) return null;
3023379af09SAndreas Gohr        return $result['cluster'];
3033379af09SAndreas Gohr    }
3043379af09SAndreas Gohr
3053379af09SAndreas Gohr    /**
3063379af09SAndreas Gohr     * Check if clustering has been done before
3073379af09SAndreas Gohr     * @return bool
3083379af09SAndreas Gohr     */
3093379af09SAndreas Gohr    protected function hasClusters()
3103379af09SAndreas Gohr    {
3113379af09SAndreas Gohr        $query = 'SELECT COUNT(*) FROM clusters';
3123379af09SAndreas Gohr        return $this->db->queryValue($query) > 0;
3133379af09SAndreas Gohr    }
314f6ef2e50SAndreas Gohr}
315