'application/json' ]; // Body for the Gemini API $body = [ 'contents' => [ [ 'parts' => [ ['text' => $prompt] ] ] ] ]; // Args for the WordPress HTTP API $args = [ 'method' => 'POST', 'headers' => $headers, 'body' => json_encode($body), 'timeout' => 120 ]; // Send the request $response = wp_remote_request($api_url, $args); // Check for request errors if (is_wp_error($response)) { return 'Error: ' . $response->get_error_message(); } // Extract the body from the response $responseBody = wp_remote_retrieve_body($response); // Log the raw response body for debugging error_log(print_r($responseBody, true)); // Decode the JSON response body $decoded = json_decode($responseBody, true); // Check for API error in response if (isset($decoded['error'])) { return 'Error: ' . $decoded['error']['message']; } // Extract the text from the response if (isset($decoded['candidates'][0]['content']['parts'][0]['text'])) { return $decoded['candidates'][0]['content']['parts'][0]['text']; } else { return 'Error: Failed to retrieve response from Gemini API.'; } }