api_key = $api_key; $this->initializeModels(); } /** * Base request configuration for a model: Gemma ships its own prescribed * sampling configuration (model card: temperature=1.0, top_p=0.95, * top_k=64), so it does not inherit the Gemini defaults. * * @param string $model Gemini API model ID. * @param int $max_tokens Output ceiling. * @return array */ private static function baseConfig( string $model, int $max_tokens ): array { if ( 0 === strpos( $model, 'gemma-' ) ) { return [ 'max_tokens' => $max_tokens, 'temperature' => 1.0, 'top_p' => 0.95, 'top_k' => 64, 'supports_system_message' => true, ]; } return [ 'max_tokens' => $max_tokens, 'temperature' => 0.7, 'supports_system_message' => true, ]; } /** * Initialize model configurations using shared base configurations * This eliminates code duplication and makes maintenance easier */ private function initializeModels(): void { $this->models = []; foreach ( ModelCatalog::get_models( 'gemini' ) as $model ) { $this->models[ $model ] = [ 'name' => $model ] + self::baseConfig( $model, 8192 ) + ModelCatalog::get_capabilities( 'gemini', $model ); } } /** * The configuration of a catalog model or of a model the site owner added * ({@see \AIPT\Api\CustomModelStore}). A custom id sends no sampling * (a gemma- id keeps Gemma's) and takes its output ceiling and structured * output from the stored lookup. * * @param string $model Gemini API model ID. * @return array * @throws ProviderCallException MODEL_NOT_FOUND for an id that is neither. */ private function getModelConfig( string $model ): array { if ( isset( $this->models[ $model ] ) ) { return $this->models[ $model ]; } $custom = ModelCatalog::get_custom_model( 'gemini', $model ); if ( null === $custom ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( 'Invalid model selected: ' . esc_html( $model ), ProviderCallException::MODEL_NOT_FOUND, null, '', null, 'gemini' ); } return $this->withSamplingParameters( [ 'name' => $model ] + self::baseConfig( $model, min( 8192, (int) $custom['caps']['max_tokens'] ) ) + ModelCatalog::get_capabilities( 'gemini', $model ) ); } /** * The generateContent URL of a model. The id is encoded so it can never * change the path, whatever reached this far. * * @param string $model Gemini API model ID. * @return string */ private function generateContentUrl( string $model ): string { return $this->api_url . '/' . rawurlencode( $model ) . ':generateContent'; } public function generate_description(string $system_prompt, string $user_prompt, string $model = '', ?int $maximum_length = null): string { $model = '' !== $model ? $model : ModelCatalog::get_default_model( 'gemini' ); $model_config = $this->getModelConfig( $model ); $endpoint = $this->generateContentUrl( $model ); $system_prompt = $this->sanitize_prompt_content($system_prompt); $user_prompt = $this->sanitize_prompt_content($user_prompt); $generation_config = []; if ( ! empty( $model_config['supports_temperature'] ) ) { $generation_config['temperature'] = $model_config['temperature']; } if ( ! empty( $model_config['supports_top_p'] ) && isset( $model_config['top_p'] ) ) { $generation_config['topP'] = $model_config['top_p']; } if ( ! empty( $model_config['supports_top_k'] ) && isset( $model_config['top_k'] ) ) { $generation_config['topK'] = $model_config['top_k']; } $request_body = [ 'contents' => [ [ 'parts' => [ ['text' => $system_prompt . "\n\n" . $user_prompt] ] ] ], ]; if ( ! empty( $generation_config ) ) { $request_body['generationConfig'] = $generation_config; } $json_body = RequestBodyEncoder::encode( $request_body, 'gemini', esc_html__( 'Failed to encode request body as JSON. The product data may contain invalid characters.', 'ai-product-tools' ), JSON_UNESCAPED_UNICODE ); $response = wp_remote_post($endpoint, [ 'headers' => [ 'Content-Type' => 'application/json', 'x-goog-api-key' => $this->api_key, ], 'body' => $json_body, 'timeout' => 30, ]); if ( $response instanceof \WP_Error ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw TransportFailure::exception( 'Gemini', $response, false ); } $decoded = DecodedResponse::read( $response, 'gemini', true, false ); $response_code = $decoded->code(); $retry_after_header = $decoded->retryAfter(); $body = $decoded->body(); if (isset($body['error'])) { $error_data = $body['error']; $detailed_error = ErrorHandler::format_api_response_error($error_data, 'Gemini', $response_code); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw self::providerErrorFromResponse( $error_data, (int) $response_code, $detailed_error, $retry_after_header ); } $text_value = $body['candidates'][0]['content']['parts'][0]['text'] ?? null; if ( null === $text_value || '' === trim( (string) $text_value ) ) { $finish_reason = $this->extractFinishReason( $body ); // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( 'Invalid response from Gemini API: Response structure is not as expected', $this->classifyEmptyContentReason( $finish_reason ), (int) $response_code, $finish_reason, null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } self::throwIfNonEmptyTextWasCutOffOrBlocked( $this->extractFinishReason( $body ), (int) $response_code ); self::trackUsage( $body, (string) $model ); return trim($body['candidates'][0]['content']['parts'][0]['text']); } public function generate_faq_content(string $system_prompt, string $user_prompt, ?string $model = null): string { $resolved_model = $model ?: ModelCatalog::get_default_model( 'gemini' ); return $this->generate_description($system_prompt, $user_prompt, $resolved_model); } public function generate_from_vision(string $system_prompt, string $user_prompt, string $image_url, ?string $model = null): string { $resolved_model = $model ?: ModelCatalog::get_default_model( 'gemini' ); $model_config = $this->getModelConfig( $resolved_model ); $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof \WP_Error ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw ProviderCallException::aiDisabled( $ai_gate, 'gemini' ); } try { $encoded_image = VisionImageEncoder::fetchAndEncode( $image_url ); } catch ( \RuntimeException $e ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw VisionImageFailure::exception( 'Gemini', $e ); } $endpoint = $this->generateContentUrl( $resolved_model ); $generation_config = []; if ( ! empty( $model_config['supports_temperature'] ) ) { $generation_config['temperature'] = $model_config['temperature']; } if ( ! empty( $model_config['supports_top_p'] ) && isset( $model_config['top_p'] ) && is_numeric( $model_config['top_p'] ) ) { $generation_config['topP'] = (float) $model_config['top_p']; } if ( ! empty( $model_config['supports_top_k'] ) && isset( $model_config['top_k'] ) && is_numeric( $model_config['top_k'] ) ) { $generation_config['topK'] = (int) $model_config['top_k']; } $request_body = [ 'contents' => [ [ 'parts' => [ [ 'text' => $this->sanitize_prompt_content( $system_prompt ) . "\n\n" . $this->sanitize_prompt_content( $user_prompt ) ], [ 'inlineData' => [ 'mimeType' => $encoded_image['mime_type'], 'data' => $encoded_image['data'], ], ], ], ], ], ]; if ( ! empty( $generation_config ) ) { $request_body['generationConfig'] = $generation_config; } $json_body = RequestBodyEncoder::encode( $request_body, 'gemini', esc_html__( 'Failed to encode vision request body as JSON.', 'ai-product-tools' ), JSON_UNESCAPED_UNICODE ); $response = wp_remote_post( $endpoint, [ 'headers' => [ 'Content-Type' => 'application/json', 'x-goog-api-key' => $this->api_key, ], 'body' => $json_body, 'timeout' => 60, ] ); if ( $response instanceof \WP_Error ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw TransportFailure::exception( 'Gemini', $response, true ); } $decoded = DecodedResponse::read( $response, 'gemini', true, true ); $response_code = $decoded->code(); $retry_after_header = $decoded->retryAfter(); $body = $decoded->body(); if ( isset( $body['error'] ) ) { $detailed_error = ErrorHandler::format_api_response_error( $body['error'], 'Gemini', $response_code ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw self::providerErrorFromResponse( $body['error'], (int) $response_code, $detailed_error, $retry_after_header ); } $vision_text = $body['candidates'][0]['content']['parts'][0]['text'] ?? null; if ( null === $vision_text || '' === trim( (string) $vision_text ) ) { $finish_reason = $this->extractFinishReason( $body ); // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( 'Invalid response from Gemini vision API: unexpected structure', $this->classifyEmptyContentReason( $finish_reason ), (int) $response_code, $finish_reason, null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } self::throwIfNonEmptyTextWasCutOffOrBlocked( $this->extractFinishReason( $body ), (int) $response_code ); self::trackUsage( $body, (string) $resolved_model ); return trim( (string) $body['candidates'][0]['content']['parts'][0]['text'] ); } /** * Generate a structured (JSON-schema-shaped) answer. * * Additive method for StructuredOutputClientInterface. When * $options['native'] is true this sets * `generationConfig.responseMimeType = 'application/json'` and * `generationConfig.responseSchema` to a Gemini-OpenAPI-subset version of * $json_schema; otherwise it sends a plain prompt call (the caller has * already appended the JSON instruction to $user_prompt) and returns * `decoded: null`. Respects the existing "never send an empty * generationConfig array" rule. Does not change generate_description()'s * request body or behavior. * * @param string $system_prompt System instructions. * @param string $user_prompt User message/prompt. * @param array $json_schema JSON schema of the expected answer. * @param string $model Model ID ('' = default). * @param array $options See StructuredOutputClientInterface. * @return array{raw_text: string, decoded: array|null, used_native: bool, model: string} */ public function generate_structured( string $system_prompt, string $user_prompt, array $json_schema, string $model = '', array $options = array() ): array { $resolved_model = '' !== $model ? $model : ModelCatalog::get_default_model( 'gemini' ); $model_config = $this->getModelConfig( $resolved_model ); $native = ! empty( $options['native'] ); $system_prompt = $this->sanitize_prompt_content( $system_prompt ); $user_prompt = $this->sanitize_prompt_content( $user_prompt ); $endpoint = $this->generateContentUrl( $resolved_model ); $generation_config = []; if ( ! empty( $model_config['supports_temperature'] ) ) { $generation_config['temperature'] = $model_config['temperature']; } if ( ! empty( $model_config['supports_top_p'] ) && isset( $model_config['top_p'] ) ) { $generation_config['topP'] = $model_config['top_p']; } if ( ! empty( $model_config['supports_top_k'] ) && isset( $model_config['top_k'] ) ) { $generation_config['topK'] = $model_config['top_k']; } if ( $native ) { $generation_config['responseMimeType'] = 'application/json'; $generation_config['responseSchema'] = $this->to_gemini_schema( $json_schema ); } $max_tokens = isset( $options['max_tokens'] ) ? (int) $options['max_tokens'] : 0; if ( $max_tokens > 0 ) { $generation_config['maxOutputTokens'] = $max_tokens; } $parts = [ [ 'text' => $system_prompt . "\n\n" . $user_prompt ] ]; if ( ! empty( $options['image']['url'] ) ) { $parts[] = $this->build_vision_part( (string) $options['image']['url'] ); } $request_body = [ 'contents' => [ [ 'parts' => $parts, ], ], ]; if ( ! empty( $generation_config ) ) { $request_body['generationConfig'] = $generation_config; } $json_body = RequestBodyEncoder::encode( $request_body, 'gemini', esc_html__( 'Failed to encode request body as JSON. The product data may contain invalid characters.', 'ai-product-tools' ), JSON_UNESCAPED_UNICODE ); $timeout = isset( $options['timeout'] ) && (int) $options['timeout'] > 0 ? (int) $options['timeout'] : 30; $response = wp_remote_post($endpoint, [ 'headers' => [ 'Content-Type' => 'application/json', 'x-goog-api-key' => $this->api_key, ], 'body' => $json_body, 'timeout' => $timeout, ]); if ( $response instanceof \WP_Error ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw TransportFailure::exception( 'Gemini', $response, false ); } $decoded = DecodedResponse::read( $response, 'gemini', true, false ); $response_code = $decoded->code(); $retry_after_header = $decoded->retryAfter(); $body = $decoded->body(); if (isset($body['error'])) { $detailed_error = ErrorHandler::format_api_response_error($body['error'], 'Gemini', $response_code); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw self::providerErrorFromResponse( $body['error'], (int) $response_code, $detailed_error, $retry_after_header ); } $text_value = $body['candidates'][0]['content']['parts'][0]['text'] ?? null; if ( null === $text_value || '' === trim( (string) $text_value ) ) { $finish_reason = $this->extractFinishReason( $body ); // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( 'Invalid response from Gemini API: Response structure is not as expected', $this->classifyEmptyContentReason( $finish_reason ), (int) $response_code, $finish_reason, null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } self::throwIfTruncatedAndUndecodable( $this->extractFinishReason( $body ), (string) $text_value, (int) $response_code ); $text = (string) $body['candidates'][0]['content']['parts'][0]['text']; $decoded = null; if ( $native ) { $maybe = json_decode( $text, true ); if ( JSON_ERROR_NONE === json_last_error() && is_array( $maybe ) ) { $decoded = $maybe; } } self::trackUsage( $body, (string) $resolved_model ); return [ 'raw_text' => trim( $text ), 'decoded' => $decoded, 'used_native' => $native, 'model' => $resolved_model, ]; } /** * Convert a strict-friendly JSON schema to Gemini's OpenAPI-3.0 subset by * recursively stripping keys the `responseSchema` field does not accept * (e.g. `additionalProperties`, `$schema`, `$id`). The schemas this * engine produces are plain object/array/string/number trees (every * property required, no oneOf/anyOf/$ref), so no further conversion is * needed. * * @param array $schema JSON schema. * @return array Gemini-compatible schema. */ private function to_gemini_schema( array $schema ): array { unset( $schema['additionalProperties'], $schema['$schema'], $schema['$id'] ); if ( isset( $schema['properties'] ) && is_array( $schema['properties'] ) ) { $properties = []; foreach ( $schema['properties'] as $key => $value ) { $properties[ $key ] = is_array( $value ) ? $this->to_gemini_schema( $value ) : $value; } $schema['properties'] = $properties; } if ( isset( $schema['items'] ) && is_array( $schema['items'] ) ) { $schema['items'] = $this->to_gemini_schema( $schema['items'] ); } return $schema; } /** * Build a Gemini `inlineData` part for one vision image, reusing the * same fetch/encode path as generate_from_vision(). * * @param string $image_url Image URL or data URI. * @return array */ private function build_vision_part( string $image_url ): array { try { $encoded_image = VisionImageEncoder::fetchAndEncode( $image_url ); } catch ( \RuntimeException $e ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw VisionImageFailure::exception( 'Gemini', $e ); } return [ 'inlineData' => [ 'mimeType' => $encoded_image['mime_type'], 'data' => $encoded_image['data'], ], ]; } /** * Cleans the prompt content and prepares it for the API * * Outbound prompt text, not AI output: cleanOutboundPrompt() skips * cleanContent()'s "repair unclosed markdown" step, which otherwise * deletes a prompt's own literal ** / * characters (e.g. an * anti-markdown rule) before the model ever sees them. * * @param string $content Prompt content to clean * @return string Cleaned content */ private function sanitize_prompt_content(string $content): string { return PromptFormatter::cleanOutboundPrompt($content); } /** * Record one answered call. promptTokenCount counts every prompt token, * the ones Gemini read from its implicit cache included; * cachedContentTokenCount lets the cost price those at the cache rate. * A thinking model's thoughts are billed as output but counted apart * from the answer (thoughtsTokenCount), so the output is both. * * @param array $body Decoded response body. * @param string $model Model identifier. * @return void */ private static function trackUsage( array $body, string $model ): void { $usage = is_array( $body['usageMetadata'] ?? null ) ? $body['usageMetadata'] : []; \AIPT\Core\Services\UsageTracker::trackApiCall( 'gemini', $model, (int) ( $usage['promptTokenCount'] ?? 0 ), (int) ( $usage['candidatesTokenCount'] ?? 0 ) + (int) ( $usage['thoughtsTokenCount'] ?? 0 ), 0, (int) ( $usage['cachedContentTokenCount'] ?? 0 ) ); } /** * Build a ProviderCallException from a Gemini error response body, * classifying its reason from the HTTP status plus the `status` string * Gemini's own error object carries (e.g. "UNAVAILABLE", "RESOURCE_EXHAUSTED"). * * @param mixed $error_data `$body['error']` from the response. * @param int $response_code HTTP status code. * @param string $detailed_error Already-formatted technical message (unchanged `getMessage()`). * @return ProviderCallException */ private static function providerErrorFromResponse( $error_data, int $response_code, string $detailed_error, ?int $retry_after_header = null ): ProviderCallException { $data = is_array( $error_data ) ? $error_data : array(); $status = isset( $data['status'] ) && is_string( $data['status'] ) ? $data['status'] : ''; $message = isset( $data['message'] ) && is_string( $data['message'] ) ? $data['message'] : ''; $details = isset( $data['details'] ) && is_array( $data['details'] ) ? $data['details'] : array(); return new ProviderCallException( $detailed_error, self::classifyErrorReason( $response_code, $status, $message, $details ), $response_code, $status, $retry_after_header ?? ErrorHandler::extract_retry_after( $error_data ), 'gemini' ); } /** * Classify a Gemini error response into a stable ProviderCallException reason. * * @param int $response_code HTTP status code. * @param string $status `error.status`, e.g. "UNAVAILABLE", "RESOURCE_EXHAUSTED". * @param string $message `error.message`, used as a fallback signal and to spot a schema-shaped 400. * @param array $details Parsed `error.details[]`, carrying the structured ErrorInfo/QuotaFailure signals below. * @return string */ private static function classifyErrorReason( int $response_code, string $status, string $message, array $details = array() ): string { $upper_status = strtoupper( $status ); if ( 401 === $response_code || 'UNAUTHENTICATED' === $upper_status ) { return ProviderCallException::AUTH_INVALID_KEY; } if ( ( 400 === $response_code || 'INVALID_ARGUMENT' === $upper_status ) && ( self::has_error_info_reason( $details, 'API_KEY_INVALID' ) || false !== stripos( $message, 'api key' ) ) ) { return ProviderCallException::AUTH_INVALID_KEY; } if ( 403 === $response_code || 'PERMISSION_DENIED' === $upper_status ) { return ProviderCallException::AUTH_FORBIDDEN; } if ( 404 === $response_code || 'NOT_FOUND' === $upper_status ) { return ProviderCallException::MODEL_NOT_FOUND; } if ( 429 === $response_code || 'RESOURCE_EXHAUSTED' === $upper_status ) { return ErrorHandler::gemini_quota_violation_is_daily_or_billing( $details ) ? ProviderCallException::QUOTA_EXHAUSTED : ProviderCallException::RATE_LIMITED; } if ( 400 === $response_code || 'INVALID_ARGUMENT' === $upper_status ) { $looks_like_token_limit = false !== stripos( $message, 'token count' ) && false !== stripos( $message, 'exceed' ); if ( $looks_like_token_limit ) { return ProviderCallException::REQUEST_TOO_LARGE; } $looks_like_schema = false !== stripos( $message, 'responseSchema' ) || false !== stripos( $message, 'response_schema' ) || false !== stripos( $message, 'schema' ); return $looks_like_schema ? ProviderCallException::INVALID_SCHEMA_REQUEST : ProviderCallException::BAD_REQUEST; } if ( $response_code >= 500 || 'UNAVAILABLE' === $upper_status || 'INTERNAL' === $upper_status ) { return ProviderCallException::PROVIDER_UNAVAILABLE; } return ProviderCallException::BAD_REQUEST; } /** * Whether Gemini's `error.details[]` carries an ErrorInfo object with the * given machine-readable `reason` (e.g. "API_KEY_INVALID"), Google's * documented stable signal, preferred over matching the message text. * * @param array $details Parsed `error.details[]`. * @param string $reason Reason to match, e.g. "API_KEY_INVALID". * @return bool */ private static function has_error_info_reason( array $details, string $reason ): bool { foreach ( $details as $detail ) { if ( ! is_array( $detail ) ) { continue; } $type = isset( $detail['@type'] ) && is_string( $detail['@type'] ) ? $detail['@type'] : ''; if ( false === stripos( $type, 'ErrorInfo' ) ) { continue; } if ( isset( $detail['reason'] ) && is_string( $detail['reason'] ) && strtoupper( $detail['reason'] ) === strtoupper( $reason ) ) { return true; } } return false; } /** * A non-empty answer can still be a cutoff or a safety block rather than a * complete success: `finishReason` describes how generation ended, * independent of whether any text came back with it. * * @param string $finish_reason Gemini `candidates[0].finishReason` (or `promptFeedback.blockReason`). * @param int $response_code HTTP status code. * @throws ProviderCallException When the answer was cut off or blocked mid-generation. */ private static function throwIfNonEmptyTextWasCutOffOrBlocked( string $finish_reason, int $response_code ): void { $normalized = strtoupper( $finish_reason ); if ( 'MAX_TOKENS' === $normalized ) { // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( 'Invalid response from Gemini API: the answer was cut off before it finished', ProviderCallException::TRUNCATED_OUTPUT, $response_code, $finish_reason, null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } self::throwIfBlocked( $finish_reason, $response_code ); } /** * A safety finish means the model declined part way through: whatever * text came back is never a usable answer, plain or structured. * * @param string $finish_reason Gemini finish reason. * @param int $response_code HTTP status code. * @throws ProviderCallException When the model declined to finish. */ private static function throwIfBlocked( string $finish_reason, int $response_code ): void { $normalized = strtoupper( $finish_reason ); if ( in_array( $normalized, array( 'SAFETY', 'RECITATION', 'BLOCKLIST', 'PROHIBITED_CONTENT', 'SPII' ), true ) ) { // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( 'Invalid response from Gemini API: the model declined partway through the answer', ProviderCallException::CONTENT_BLOCKED, $response_code, $finish_reason, null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } } /** * generate_structured()'s own truncation rule: a length cutoff only fails * the call when the text it cut off does not even decode as JSON. * * @param string $finish_reason Gemini `candidates[0].finishReason`. * @param string $text Raw text content. * @param int $response_code HTTP status code. * @throws ProviderCallException When a length cutoff left undecodable JSON. */ private static function throwIfTruncatedAndUndecodable( string $finish_reason, string $text, int $response_code ): void { self::throwIfBlocked( $finish_reason, $response_code ); if ( 'MAX_TOKENS' !== strtoupper( $finish_reason ) ) { return; } $maybe = json_decode( $text, true ); if ( JSON_ERROR_NONE === json_last_error() && is_array( $maybe ) ) { return; } // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( 'Invalid response from Gemini API: the answer was cut off before it finished', ProviderCallException::TRUNCATED_OUTPUT, $response_code, $finish_reason, null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } /** * Classify why the model's content came back empty: a safety refusal and * a length cutoff both need their own reason instead of the generic * "unexpected structure" bucket. * * @param string $finish_reason Gemini `candidates[0].finishReason` (or `promptFeedback.blockReason`). * @return string */ /** * Read why Gemini produced no candidate text: the per-candidate * `finishReason`, or, when the prompt itself was blocked before any * candidate was generated, `promptFeedback.blockReason`. * * @param array $body Decoded response body. * @return string */ private function extractFinishReason( array $body ): string { if ( isset( $body['candidates'][0]['finishReason'] ) && is_string( $body['candidates'][0]['finishReason'] ) ) { return $body['candidates'][0]['finishReason']; } if ( isset( $body['promptFeedback']['blockReason'] ) && is_string( $body['promptFeedback']['blockReason'] ) ) { return $body['promptFeedback']['blockReason']; } return ''; } private function classifyEmptyContentReason( string $finish_reason ): string { $normalized = strtoupper( $finish_reason ); if ( in_array( $normalized, array( 'SAFETY', 'RECITATION', 'BLOCKLIST', 'PROHIBITED_CONTENT', 'SPII' ), true ) ) { return ProviderCallException::CONTENT_BLOCKED; } if ( 'MAX_TOKENS' === $normalized ) { return ProviderCallException::TRUNCATED_OUTPUT; } return ProviderCallException::MALFORMED_RESPONSE; } public static function validate_api_key(string $api_key): bool { $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models'; $response = wp_remote_get($endpoint, [ 'headers' => [ 'Content-Type' => 'application/json', 'x-goog-api-key' => $api_key, ], 'timeout' => 20 ]); if (is_wp_error($response)) { /** @var \WP_Error $response */ // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw TransportFailure::exception( 'Gemini', $response, false ); } $response_code = (int) wp_remote_retrieve_response_code($response); $content_type = (string) wp_remote_retrieve_header( $response, 'content-type' ); $body_str = (string) wp_remote_retrieve_body($response); HtmlBodyGuard::throwIfHtml( 'gemini', $content_type, $body_str, $response_code, true ); if ( 429 === $response_code || $response_code >= 500 ) { $failure = json_decode( $body_str, true ); if ( ! is_array( $failure ) || ! isset( $failure['error'] ) ) { // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %d: HTTP status code */ __( 'Unexpected response from Gemini API (HTTP %d).', 'ai-product-tools' ), $response_code ), 429 === $response_code ? ProviderCallException::RATE_LIMITED : ProviderCallException::PROVIDER_UNAVAILABLE, $response_code, '', null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } } $body = json_decode($body_str, true); if (json_last_error() !== JSON_ERROR_NONE || !is_array($body)) { // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %s: JSON error message */ __('Invalid response from Gemini API: %s', 'ai-product-tools'), json_last_error_msg() ), ProviderCallException::MALFORMED_RESPONSE, $response_code, '', null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ($response_code === 200 && isset($body['models'])) { return true; } if (isset($body['error'])) { $error_data = $body['error']; $detailed_error = ErrorHandler::format_api_response_error($error_data, 'Gemini', $response_code); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw self::providerErrorFromResponse( $error_data, $response_code, $detailed_error, null ); } // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %d: HTTP status code */ __( 'Unexpected response from Gemini API (HTTP %d).', 'ai-product-tools' ), $response_code ), $response_code >= 500 ? ProviderCallException::PROVIDER_UNAVAILABLE : ProviderCallException::MALFORMED_RESPONSE, $response_code, '', null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } /** * Look a model id up with the models API before the site owner adds it * ({@see CustomModelStore}): one metadata GET with the key check's headers * and timeout, which costs no tokens. A leading `models/` is dropped. * * The model must list generateContent and not belong to a family that * writes something other than text. A Gemma id takes no native structured * output, as the catalog's Gemma models do. * * @param string $model Model id. * @return array{label: string, status: string, caps: array} * @throws ModelLookupRefusal Why the id cannot be added. */ public function lookup_model( string $model ): array { $id = 0 === strpos( $model, 'models/' ) ? substr( $model, 7 ) : $model; try { $body = $this->fetchModel( $id ); } catch ( ProviderCallException $e ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception; a refusal carries its own fixed sentence. throw ModelLookupRefusal::fromProviderFailure( $e ); } return self::modelLookupResult( $body, $id ); } /** * The decoded Model resource of a 200 answer. The key goes in a header, * never in the URL. * * @param string $id Model id without `models/`. * @return array * @throws ProviderCallException When the call failed. * @throws ModelLookupRefusal NOT_FOUND when Gemini answered NOT_FOUND. */ private function fetchModel( string $id ): array { $response = wp_remote_get( $this->api_url . '/' . rawurlencode( $id ), [ 'headers' => [ 'Content-Type' => 'application/json', 'x-goog-api-key' => $this->api_key, ], 'timeout' => 20, ] ); if ( is_wp_error( $response ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw TransportFailure::exception( 'Gemini', $response, false ); } $response_code = (int) wp_remote_retrieve_response_code( $response ); $content_type = (string) wp_remote_retrieve_header( $response, 'content-type' ); $body_str = (string) wp_remote_retrieve_body( $response ); HtmlBodyGuard::throwIfHtml( 'gemini', $content_type, $body_str, $response_code, true ); if ( 429 === $response_code || $response_code >= 500 ) { $failure = json_decode( $body_str, true ); if ( ! is_array( $failure ) || ! isset( $failure['error'] ) ) { // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %d: HTTP status code */ __( 'Unexpected response from Gemini API (HTTP %d).', 'ai-product-tools' ), $response_code ), 429 === $response_code ? ProviderCallException::RATE_LIMITED : ProviderCallException::PROVIDER_UNAVAILABLE, $response_code, '', null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } } $body = json_decode( $body_str, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $body ) ) { // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %s: JSON error message */ __( 'Invalid response from Gemini API: %s', 'ai-product-tools' ), json_last_error_msg() ), ProviderCallException::MALFORMED_RESPONSE, $response_code, '', null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( 200 === $response_code ) { return $body; } if ( 404 === $response_code && is_array( $body['error'] ?? null ) && 'NOT_FOUND' === ( $body['error']['status'] ?? null ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception; a refusal carries its own fixed sentence. throw new ModelLookupRefusal( ModelLookupRefusal::NOT_FOUND, 'Gemini answered NOT_FOUND (HTTP 404)' ); } if ( isset( $body['error'] ) ) { $detailed_error = ErrorHandler::format_api_response_error( $body['error'], 'Gemini', $response_code ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw self::providerErrorFromResponse( $body['error'], $response_code, $detailed_error, null ); } // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %d: HTTP status code */ __( 'Unexpected response from Gemini API (HTTP %d).', 'ai-product-tools' ), $response_code ), ProviderCallException::MALFORMED_RESPONSE, $response_code, '', null, 'gemini' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exceptions below; a refusal carries its own fixed sentence. /** * What the store keeps for a Model resource, read strictly: a missing or * mistyped field refuses the id. * * @param array $body Decoded Model resource. * @param string $id Requested model id without `models/`. * @return array{label: string, status: string, caps: array} * @throws ModelLookupRefusal UNEXPECTED_ANSWER or NOT_A_CHAT_MODEL. */ private static function modelLookupResult( array $body, string $id ): array { $name = $body['name'] ?? null; $methods = $body['supportedGenerationMethods'] ?? null; if ( ! is_string( $name ) || 0 !== strpos( $name, 'models/' ) || ! is_array( $methods ) ) { throw new ModelLookupRefusal( ModelLookupRefusal::UNEXPECTED_ANSWER, 'Gemini model answer without a models/ name or supportedGenerationMethods' ); } foreach ( $methods as $method ) { if ( ! is_string( $method ) ) { throw new ModelLookupRefusal( ModelLookupRefusal::UNEXPECTED_ANSWER, 'Gemini model answer with a generation method that is not a string' ); } } $display_name = $body['displayName'] ?? null; if ( null !== $display_name && ! is_string( $display_name ) ) { throw new ModelLookupRefusal( ModelLookupRefusal::UNEXPECTED_ANSWER, 'Gemini model answer with a displayName that is not a string' ); } $max_tokens = $body['outputTokenLimit'] ?? 8192; if ( ! is_int( $max_tokens ) || $max_tokens < 1 || $max_tokens > CustomModelStore::MAX_OUTPUT_TOKENS ) { throw new ModelLookupRefusal( ModelLookupRefusal::UNEXPECTED_ANSWER, 'Gemini model answer with an unusable outputTokenLimit' ); } if ( ! in_array( 'generateContent', $methods, true ) || self::isNonTextModelId( $id ) || self::isNonTextModelId( substr( $name, 7 ) ) ) { throw new ModelLookupRefusal( ModelLookupRefusal::NOT_A_CHAT_MODEL, 'Gemini model without generateContent or in a family that does not write text' ); } return [ 'label' => CustomModelStore::clean_label( $display_name, $id ), 'status' => 'active', 'caps' => [ 'max_tokens' => $max_tokens, 'vision' => true, 'structured_output' => 0 === strpos( $id, 'gemma-' ) ? 'none' : 'json_schema', 'thinking_off' => null, ], ]; } // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped /** * @param string $id Model id without `models/`. * @return bool Whether the id belongs to a family that does not write text. */ private static function isNonTextModelId( string $id ): bool { $id = strtolower( $id ); foreach ( self::NON_TEXT_ID_PARTS as $part ) { if ( false !== strpos( $id, $part ) ) { return true; } } return false; } /** * A configuration with every setParameters() call so far applied, in order. * * @param array $model_config Model configuration. * @return array */ private function withSamplingParameters( array $model_config ): array { foreach ( $this->sampling_calls as $parameters ) { $model_config = $this->applySamplingParameters( $model_config, $parameters ); } return $model_config; } /** * Apply merchant sampling parameters to one model configuration, within * the ranges each provider accepts. The configuration is left untyped so * a write it refuses fails with its own error inside setParameters()'s * catch, as before this helper existed. * * @template T of array|\ArrayAccess * @param T $model_config Model configuration. * @param array $parameters Sampling parameters. * @return T The configuration with the parameters applied. */ private function applySamplingParameters( $model_config, array $parameters ) { if (isset($parameters['temperature']) && is_numeric($parameters['temperature'])) { $temperature = floatval($parameters['temperature']); if ($temperature >= 0.0 && $temperature <= 1.0 && ! empty( $model_config['supports_temperature'] )) { $model_config['temperature'] = $temperature; } } if (isset($parameters['top_p']) && is_numeric($parameters['top_p'])) { $topP = floatval($parameters['top_p']); if ($topP >= 0.0 && $topP <= 1.0 && ! empty( $model_config['supports_top_p'] )) { $model_config['top_p'] = $topP; } } if (isset($parameters['top_k']) && is_numeric($parameters['top_k'])) { $topK = intval($parameters['top_k']); if ($topK >= 1 && $topK <= 40 && ! empty( $model_config['supports_top_k'] )) { $model_config['top_k'] = $topK; } } return $model_config; } public function get_available_models(): array { return $this->models; } /** * Apply sampling parameters to every model of this client. * * @param array $parameters Parameters to apply. * @return void */ public function setParameters(array $parameters): void { if (empty($parameters)) { return; } $this->sampling_calls[] = $parameters; try { foreach ($this->models as $model_id => $model_config) { $this->models[ $model_id ] = $this->applySamplingParameters( $model_config, $parameters ); } } catch (\Throwable $e) { Logger::warn( 'provider', 'Gemini sampling parameters could not be applied', array( 'error' => $e->getMessage() ) ); } } }