]> BookStack Code Mirror - bookstack/blob - app/Search/Vectors/VectorSearchRunner.php
Vectors: Got basic LLM querying working using vector search context
[bookstack] / app / Search / Vectors / VectorSearchRunner.php
1 <?php
2
3 namespace BookStack\Search\Vectors;
4
5 class VectorSearchRunner
6 {
7     public function __construct(
8         protected VectorQueryServiceProvider $vectorQueryServiceProvider
9     ) {
10     }
11
12     public function run(string $query): array
13     {
14         $queryService = $this->vectorQueryServiceProvider->get();
15         $queryVector = $queryService->generateEmbeddings($query);
16
17         // TODO - Apply permissions
18         // TODO - Join models
19         $topMatches = SearchVector::query()->select('text', 'entity_type', 'entity_id')
20             ->selectRaw('VEC_DISTANCE_COSINE(VEC_FROMTEXT("[' . implode(',', $queryVector) . ']"), embedding) as distance')
21             ->orderBy('distance', 'asc')
22             ->limit(10)
23             ->get();
24
25         $matchesText = array_values(array_map(fn (SearchVector $match) => $match->text, $topMatches->all()));
26         $llmResult = $queryService->query($query, $matchesText);
27
28         return [
29             'llm_result' => $llmResult,
30             'entity_matches' => $topMatches->toArray()
31         ];
32     }
33 }