'keyword', 'post_type' => 'keyword', 'object_id' => 'integer', 'lang' => 'keyword', ]; private const UPSERT_BATCH = 256; private const DELETE_BATCH = 500; private string $url; private string $apiKey; private string $collection; public function __construct(?string $collection = null, ?string $url = null, ?string $apiKey = null) { $this->collection = $collection ?? self::configuredCollection(); $this->url = rtrim($url ?? (string) (get_plugin_settings()['qdrant_url'] ?? ''), '/'); $this->apiKey = $apiKey ?? self::apiKey(); } public function id(): string { return 'qdrant'; } public function indexName(): string { return $this->collection; } public function isSiteOwn(): bool { return trim((string) (get_plugin_settings()['qdrant_collection'] ?? '')) === ''; } public static function apiKey(): string { $key = trim((string) (get_plugin_settings()['qdrant_api_key'] ?? '')); if ($key === '' && defined('AIPCF_QDRANT_API_KEY') && is_string(\AIPCF_QDRANT_API_KEY)) { $key = \AIPCF_QDRANT_API_KEY; } return $key; } public static function configuredCollection(): string { $custom = trim((string) (get_plugin_settings()['qdrant_collection'] ?? '')); if ($custom !== '') { return self::sanitizeName($custom); // may be shared: never suffixed, never dropped } $name = 'aipcf-' . (string) wp_parse_url(home_url(), PHP_URL_HOST); if (is_multisite() && !is_main_site()) { $name .= '-' . get_current_blog_id(); } return State::suffixed(self::sanitizeName($name), 255); } public static function sanitizeName(string $name): string { $name = (string) preg_replace('/[^a-z0-9_-]+/', '-', strtolower($name)); $name = trim((string) preg_replace('/-+/', '-', $name), '-_'); return $name !== '' ? substr($name, 0, 255) : 'aipcf'; } /** * A deterministic UUID for a vector ID (Qdrant accepts UUIDs or integers only). */ public static function pointId(string $vectorId): string { $h = md5('aipcf|' . $vectorId); // Version 5-style and RFC 4122 variant bits, so strict parsers accept it. $h[12] = '5'; $h[16] = dechex(8 | (hexdec($h[16]) & 3)); return sprintf('%s-%s-%s-%s-%s', substr($h, 0, 8), substr($h, 8, 4), substr($h, 12, 4), substr($h, 16, 4), substr($h, 20, 12)); } public function test() { $r = $this->request('GET', '/collections'); return is_wp_error($r) ? $r : true; } public function ensureIndex(int $dims, string $metric = 'cosine') { $created = false; $info = $this->request('GET', $this->path()); if (is_wp_error($info) && $info->get_error_code() === 'aipcf_store_missing') { $r = $this->request('PUT', $this->path(), ['vectors' => ['size' => $dims, 'distance' => 'Cosine']]); if (is_wp_error($r) && ($r->get_error_data()['status'] ?? 0) !== 409) { return $r; } $created = !is_wp_error($r); $info = $this->request('GET', $this->path()); } if (is_wp_error($info)) { return $info; } $shape = self::shape($info); if ($shape['dims'] !== $dims || $shape['metric'] !== $metric) { // Rebuild starts a new collection only for the site's own one; a custom name is re-embedded in place. return new \WP_Error('aipcf_store_mismatch', sprintf( $this->isSiteOwn() /* translators: 1: collection name, 2: numbers in each stored vector, 3: how the collection compares vectors, 4: numbers in each vector the model makes, 5: how the model's vectors are compared */ ? __('The Qdrant collection %1$s holds vectors of %2$d numbers compared by %3$s, but the embedding model needs vectors of %4$d numbers compared by %5$s. Press Rebuild (under More actions) to start a new collection.', 'aipcf-ai-provider-for-cloudflare') /* translators: 1: collection name, 2: numbers in each stored vector, 3: how the collection compares vectors, 4: numbers in each vector the model makes, 5: how the model's vectors are compared */ : __('The Qdrant collection %1$s holds vectors of %2$d numbers compared by %3$s, but the embedding model needs vectors of %4$d numbers compared by %5$s. Enter a new collection name, or go back to a model with the same vector size.', 'aipcf-ai-provider-for-cloudflare'), $this->collection, $shape['dims'], $shape['metric'] !== '' ? $shape['metric'] : '-', $dims, $metric )); } foreach (self::PAYLOAD_INDEXES as $field => $schema) { if (in_array($field, $shape['indexed'], true)) { continue; } // Idempotent in Qdrant: creating an existing payload index succeeds. $r = $this->request('PUT', $this->path() . '/index?wait=true', ['field_name' => $field, 'field_schema' => $schema]); if (is_wp_error($r)) { return $r; } } return ['created' => $created]; } public function status() { $info = $this->request('GET', $this->path()); if (is_wp_error($info)) { if ($info->get_error_code() === 'aipcf_store_missing') { return ['exists' => false, 'ready' => false, 'dims' => 0, 'metric' => '', 'vector_count' => null, 'settled' => true, 'missing_metadata' => array_keys(self::PAYLOAD_INDEXES)]; } return $info; } $shape = self::shape($info); $missing = array_values(array_diff(array_keys(self::PAYLOAD_INDEXES), $shape['indexed'])); return [ 'exists' => true, 'ready' => $missing === [], 'dims' => $shape['dims'], 'metric' => $shape['metric'], 'vector_count' => isset($info['points_count']) ? (int) $info['points_count'] : null, 'settled' => true, 'missing_metadata' => $missing, ]; } public function upsert(array $vectors) { $points = []; $bad = []; foreach ($vectors as $v) { $id = (string) ($v['id'] ?? ''); if ($id === '') { $bad[] = $id; continue; } $points[] = [ 'id' => self::pointId($id), 'vector' => array_map(static fn($x): float => round((float) $x, 6), array_values((array) ($v['values'] ?? []))), 'payload' => ['vid' => $id] + (is_array($v['metadata'] ?? null) ? $v['metadata'] : []), ]; } if ($bad !== []) { return new \WP_Error('aipcf_store_item', __('A vector has an empty ID.', 'aipcf-ai-provider-for-cloudflare'), ['ids' => $bad]); } foreach (array_chunk($points, self::UPSERT_BATCH) as $batch) { $r = $this->request('PUT', $this->path() . '/points?wait=true', ['points' => $batch], 120); if (is_wp_error($r)) { return $r; } } return true; } public function delete(array $ids) { $ids = array_values(array_filter(array_map('strval', $ids), static fn($id): bool => $id !== '')); foreach (array_chunk($ids, self::DELETE_BATCH) as $batch) { $r = $this->request('POST', $this->path() . '/points/delete?wait=true', ['points' => array_map([self::class, 'pointId'], $batch)]); if (is_wp_error($r)) { return $r; } } return true; } public function query(array $vector, int $topK = 10, array $filter = [], bool $withMetadata = true) { $body = [ 'vector' => array_map('floatval', array_values($vector)), 'limit' => max(1, min($topK, 100)), // The original ID is in the payload, so ask for at least that field. 'with_payload' => $withMetadata ? true : ['vid'], ]; if ($filter !== []) { $must = []; foreach ($filter as $key => $value) { $must[] = ['key' => (string) $key, 'match' => ['value' => $value]]; } $body['filter'] = ['must' => $must]; } $r = $this->request('POST', $this->path() . '/points/search', $body); if (is_wp_error($r)) { return $r; } $out = []; foreach ($r as $point) { if (!is_array($point)) { continue; } $payload = is_array($point['payload'] ?? null) ? $point['payload'] : []; $id = (string) ($payload['vid'] ?? $point['id'] ?? ''); unset($payload['vid']); $out[] = ['id' => $id, 'score' => (float) ($point['score'] ?? 0), 'metadata' => $withMetadata ? $payload : []]; } return $out; } public function vectors(array $ids) { $ids = array_values(array_unique(array_filter(array_map('strval', $ids), static fn($id): bool => $id !== ''))); $out = []; foreach (array_chunk($ids, self::DELETE_BATCH) as $batch) { $r = $this->request('POST', $this->path() . '/points', ['ids' => array_map([self::class, 'pointId'], $batch), 'with_vector' => true, 'with_payload' => ['vid']]); if (is_wp_error($r)) { return $r; } foreach ((array) $r as $point) { $vid = is_array($point) ? (string) ($point['payload']['vid'] ?? '') : ''; $vector = is_array($point) ? ($point['vector'] ?? null) : null; if ($vid !== '' && is_array($vector)) { $out[$vid] = array_map('floatval', array_values($vector)); } } } return $out; } public function dropIndex() { $r = $this->request('DELETE', $this->path()); return is_wp_error($r) && $r->get_error_code() !== 'aipcf_store_missing' ? $r : true; } private function path(): string { return '/collections/' . rawurlencode($this->collection); } /** * @param array $info * @return array{dims: int, metric: string, indexed: list} */ private static function shape(array $info): array { $vectors = $info['config']['params']['vectors'] ?? []; $vectors = is_array($vectors) ? $vectors : []; return [ 'dims' => (int) ($vectors['size'] ?? 0), 'metric' => strtolower((string) ($vectors['distance'] ?? '')), 'indexed' => array_map('strval', array_keys(is_array($info['payload_schema'] ?? null) ? $info['payload_schema'] : [])), ]; } /** * @param array|null $body * @return array|\WP_Error The decoded `result`. */ private function request(string $method, string $path, ?array $body = null, int $timeout = 30) { if ($this->url === '' || !preg_match('#^https?://#i', $this->url)) { return new \WP_Error('aipcf_store_auth', __('Enter the Qdrant URL (for example https://xyz.cloud.qdrant.io:6333).', 'aipcf-ai-provider-for-cloudflare')); } $host = (string) wp_parse_url($this->url, PHP_URL_HOST); $check = Endpoint::check($host); if ($check['reason'] !== '') { /* translators: %s: why the address is not allowed */ return new \WP_Error('aipcf_store_auth', sprintf(__('This Qdrant address is not allowed: %s', 'aipcf-ai-provider-for-cloudflare'), $check['reason'])); } // No redirects: WordPress would resend the api-key header to wherever they point. $args = ['method' => $method, 'timeout' => $timeout, 'redirection' => 0, 'headers' => ['Content-Type' => 'application/json']]; if ($this->apiKey !== '') { $args['headers']['api-key'] = $this->apiKey; } if ($body !== null) { $args['body'] = (string) wp_json_encode($body); } // Connect to the address that was just checked, so DNS cannot swap it for another. $pin = null; if ($check['ip'] !== '') { $port = (int) (wp_parse_url($this->url, PHP_URL_PORT) ?: (stripos($this->url, 'https://') === 0 ? 443 : 80)); $ip = strpos($check['ip'], ':') !== false ? '[' . $check['ip'] . ']' : $check['ip']; $pin = static function ($handle) use ($host, $port, $ip): void { if (defined('CURLOPT_RESOLVE')) { curl_setopt($handle, CURLOPT_RESOLVE, [$host . ':' . $port . ':' . $ip]); // phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt } }; add_action('http_api_curl', $pin); } $response = wp_remote_request($this->url . $path, $args); if ($pin !== null) { remove_action('http_api_curl', $pin); } if (is_wp_error($response)) { /* translators: %s: error message */ return new \WP_Error('aipcf_retry', sprintf(__('Qdrant did not answer: %s', 'aipcf-ai-provider-for-cloudflare'), $response->get_error_message())); } $status = (int) wp_remote_retrieve_response_code($response); $data = json_decode((string) wp_remote_retrieve_body($response), true); $data = is_array($data) ? $data : []; if ($status >= 200 && $status < 300) { $result = $data['result'] ?? []; return is_array($result) ? $result : ['value' => $result]; } $detail = isset($data['status']['error']) && is_string($data['status']['error']) ? $data['status']['error'] : sprintf('HTTP %d', $status); /* translators: %s: error detail from Qdrant */ $message = sprintf(__('Qdrant returned an error: %s', 'aipcf-ai-provider-for-cloudflare'), $detail); $context = ['status' => $status]; if ($status === 429 || $status >= 500) { return new \WP_Error('aipcf_retry', $message, $context); } if ($status === 401 || $status === 403) { /* translators: %s: error detail from Qdrant */ return new \WP_Error('aipcf_store_auth', sprintf(__('Qdrant refused the API key. Check the Qdrant API key: %s', 'aipcf-ai-provider-for-cloudflare'), $detail), $context); } if ($status === 404) { return new \WP_Error('aipcf_store_missing', $message, $context); } if (stripos($detail, 'dimension') !== false) { return new \WP_Error('aipcf_store_mismatch', $message, $context); } return new \WP_Error('aipcf_store_failed', $message, $context); } }