3 namespace BookStack\Search\Vectors\Services;
5 use BookStack\Http\HttpRequestService;
7 class OpenAiVectorQueryService implements VectorQueryService
9 public function __construct(
10 protected string $endpoint,
11 protected string $key,
12 protected HttpRequestService $http,
16 protected function jsonRequest(string $method, string $uri, array $data): array
18 $fullUrl = rtrim($this->endpoint, '/') . '/' . ltrim($uri, '/');
19 $client = $this->http->buildClient(10);
20 $request = $this->http->jsonRequest($method, $fullUrl, $data)
21 ->withHeader('Authorization', 'Bearer ' . $this->key);
23 $response = $client->sendRequest($request);
24 return json_decode($response->getBody()->getContents(), true);
27 public function generateEmbeddings(string $text): array
29 $response = $this->jsonRequest('POST', 'v1/embeddings', [
31 'model' => 'text-embedding-3-small',
34 return $response['data'][0]['embedding'];
37 public function query(string $input, array $context): string
39 $formattedContext = implode("\n", $context);
41 $response = $this->jsonRequest('POST', 'v1/chat/completions', [
45 'role' => 'developer',
46 'content' => 'You are a helpful assistant providing search query responses. Be specific, factual and to-the-point in response.'
50 'content' => "Provide a response to the below given QUERY using the below given CONTEXT\nQUERY: {$input}\n\nCONTEXT: {$formattedContext}",
55 return $response['choices'][0]['message']['content'] ?? '';