provider = $provider; $this->api_key = $api_key; $this->model = $model; } public function embed(string $text, $retries = 1) { $cache_key = 'shoponix_emb_' . md5($this->provider . '_' . $text); $cached = get_transient($cache_key); if ($cached) { return $cached; } $embedding = false; if ($this->provider === 'gemini') { // Google Gemini Embedding endpoint $model = $this->model ?: 'text-embedding-004'; $url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:embedContent?key=" . $this->api_key; $response = wp_remote_post($url, [ 'headers' => [ 'Content-Type' => 'application/json' ], 'body' => json_encode([ 'content' => [ 'parts' => [ ['text' => $text] ] ] ]), 'timeout' => 30 ]); if (!is_wp_error($response)) { $body = json_decode(wp_remote_retrieve_body($response), true); $embedding = $body['embedding']['values'] ?? false; } } elseif ($this->provider === 'openai') { // OpenAI Embedding endpoint $model = $this->model ?: 'text-embedding-3-small'; $response = wp_remote_post('https://api.openai.com/v1/embeddings', [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json' ], 'body' => json_encode([ 'model' => $model, 'input' => $text ]), 'timeout' => 30 ]); if (!is_wp_error($response)) { $body = json_decode(wp_remote_retrieve_body($response), true); $embedding = $body['data'][0]['embedding'] ?? false; } } elseif ($this->provider === 'ollama') { $model = $this->model ?: 'nomic-embed-text'; $ollama_url = get_option('shoponix_ollama_url', 'http://localhost:11434'); $url = rtrim($ollama_url, '/') . '/api/embeddings'; $response = wp_remote_post($url, [ 'headers' => [ 'Content-Type' => 'application/json' ], 'body' => json_encode([ 'model' => $model, 'prompt' => $text ]), 'timeout' => 30 ]); if (!is_wp_error($response)) { $body = json_decode(wp_remote_retrieve_body($response), true); $embedding = $body['embedding'] ?? false; } } else { // Default to Mistral $model = $this->model ?: 'mistral-embed'; $response = wp_remote_post('https://api.mistral.ai/v1/embeddings', [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json' ], 'body' => json_encode([ 'model' => $model, 'input' => $text ]), 'timeout' => 30 ]); if (!is_wp_error($response)) { $status_code = wp_remote_retrieve_response_code($response); if ($status_code === 429 && $retries > 0) { sleep(2); return $this->embed($text, $retries - 1); } $body = json_decode(wp_remote_retrieve_body($response), true); $embedding = $body['data'][0]['embedding'] ?? false; } } if ($embedding) { set_transient($cache_key, $embedding, 5 * MINUTE_IN_SECONDS); } return $embedding; } }