api_key = (string) $api_key; } /** * Provider ID. * * @return string */ public function get_id() { return 'gemini'; } /** * Display name. * * @return string */ public function get_label() { return 'Google Gemini'; } /** * Default chat model. * * @return string */ public function get_default_chat_model() { return 'gemini-2.0-flash'; } /** * Default embedding model. * * @return string */ public function get_default_embedding_model() { return 'text-embedding-004'; } /** * Vector dimensions. * * @return int */ public function get_embedding_dimensions() { return 768; } /** * Confirms that the API key is accepted. * * Gemini takes the key in the query string, so this call cannot succeed without one. * * @return true|WP_Error */ public function verify_credentials() { if ( '' === $this->api_key ) { return new WP_Error( 'mybot_missing_key', __( 'No Gemini API key configured.', 'aihouse' ) ); } $url = self::ENDPOINT . '/models?key=' . rawurlencode( $this->api_key ) . '&pageSize=1'; $result = MYBOT_HTTP::get_json( $url, array(), 12 ); if ( is_wp_error( $result ) ) { return $result; } return true; } /** * Lists the models this provider offers for chat. * * Gemini has its own response shape and passes the key in the query string instead of a * header, so it cannot share the OpenAI-compatible implementation. The catalogue also * mixes chat and embedding models, and only the former belong in a model dropdown, so * anything that cannot run generateContent is dropped. * * @param string $filter One of 'all', 'free' or 'paid'. * @param bool $force Ignore the cache and ask Google again. * @return array|WP_Error */ public function list_models( $filter = 'all', $force = false ) { $filter = MYBOT_LLM_Factory::clean_model_filter( $filter ); $cache_key = MYBOT_LLM_Factory::models_cache_key( $this->get_id(), $filter ); if ( '' === $this->api_key ) { return new WP_Error( 'mybot_missing_key', __( 'No Gemini API key configured.', 'aihouse' ) ); } // Gemini bills per token like the other providers; nothing in the catalogue is free. if ( 'free' === $filter ) { return array(); } if ( ! $force ) { $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } } $url = self::ENDPOINT . '/models?key=' . rawurlencode( $this->api_key ) . '&pageSize=200'; $result = MYBOT_HTTP::get_json( $url, array(), 12 ); if ( is_wp_error( $result ) ) { return $result; } $rows = ( isset( $result['models'] ) && is_array( $result['models'] ) ) ? $result['models'] : array(); $models = array(); foreach ( $rows as $row ) { $name = isset( $row['name'] ) ? (string) $row['name'] : ''; if ( '' === $name ) { continue; } $methods = ( isset( $row['supportedGenerationMethods'] ) && is_array( $row['supportedGenerationMethods'] ) ) ? $row['supportedGenerationMethods'] : array(); if ( ! in_array( 'generateContent', $methods, true ) ) { continue; } // The API names models "models/gemini-2.0-flash"; the plugin stores them without // the prefix, which is also the form the chat endpoint expects. $id = ( 0 === strpos( $name, 'models/' ) ) ? substr( $name, 7 ) : $name; $models[] = array( 'id' => $id, 'name' => isset( $row['displayName'] ) ? (string) $row['displayName'] : $id, 'free' => false, 'context' => isset( $row['inputTokenLimit'] ) ? (int) $row['inputTokenLimit'] : 0, ); } usort( $models, function ( $a, $b ) { return strcasecmp( $a['name'], $b['name'] ); } ); set_transient( $cache_key, $models, 6 * HOUR_IN_SECONDS ); return $models; } /** * Calls generateContent. * * @param array $messages Messages. * @param array $args Arguments. * @return array|WP_Error */ public function chat( $messages, $args = array() ) { if ( '' === $this->api_key ) { return new WP_Error( 'mybot_missing_key', __( 'No Gemini API key configured.', 'aihouse' ) ); } $args = wp_parse_args( $args, array( 'model' => $this->get_default_chat_model(), 'temperature' => 0.3, 'max_tokens' => 500, 'timeout' => 8, ) ); $converted = $this->format_messages( $messages ); $body = array( 'contents' => $converted['contents'], 'generationConfig' => array( 'temperature' => (float) $args['temperature'], 'maxOutputTokens' => (int) $args['max_tokens'], ), ); if ( '' !== $converted['system'] ) { $body['systemInstruction'] = array( 'parts' => array( array( 'text' => $converted['system'] ) ), ); } $url = sprintf( '%s/models/%s:generateContent?key=%s', self::ENDPOINT, rawurlencode( $args['model'] ), rawurlencode( $this->api_key ) ); $response = MYBOT_HTTP::post_json( $url, $body, array(), (int) $args['timeout'] ); if ( is_wp_error( $response ) ) { return $response; } $content = ''; if ( isset( $response['candidates'][0]['content']['parts'] ) && is_array( $response['candidates'][0]['content']['parts'] ) ) { foreach ( $response['candidates'][0]['content']['parts'] as $part ) { if ( isset( $part['text'] ) ) { $content .= (string) $part['text']; } } } if ( '' === trim( $content ) ) { $reason = isset( $response['candidates'][0]['finishReason'] ) ? (string) $response['candidates'][0]['finishReason'] : ''; return new WP_Error( 'mybot_empty_completion', '' !== $reason /* translators: %s: reason reported by Gemini */ ? sprintf( __( 'Gemini returned no content. Reason: %s', 'aihouse' ), $reason ) : __( 'Gemini returned an empty reply.', 'aihouse' ) ); } return array( 'content' => trim( $content ), 'model' => (string) $args['model'], 'tokens_in' => isset( $response['usageMetadata']['promptTokenCount'] ) ? (int) $response['usageMetadata']['promptTokenCount'] : 0, 'tokens_out' => isset( $response['usageMetadata']['candidatesTokenCount'] ) ? (int) $response['usageMetadata']['candidatesTokenCount'] : 0, ); } /** * Generates embeddings through batchEmbedContents. * * @param array $texts List of text chunks. * @param string $model Model. * @return array|WP_Error */ public function embed( $texts, $model = '' ) { if ( '' === $this->api_key ) { return new WP_Error( 'mybot_missing_key', __( 'No Gemini API key configured.', 'aihouse' ) ); } /* * Blank entries are dropped but every surviving text keeps a note of the position it came * from: that position is what pairs a vector with its chunk (see the loop below). Re-indexing * with array_values() would shift every chunk after the first blank one — the same silent * mispairing fixed in 1.5.5 (docs/08 muc 6.22). */ $texts = array_filter( array_map( 'strval', (array) $texts ), 'strlen' ); if ( array() === $texts ) { return array(); } $dropped = array_keys( $texts ); $model = '' !== $model ? $model : $this->get_default_embedding_model(); $requests = array(); foreach ( $texts as $text ) { $requests[] = array( 'model' => 'models/' . $model, 'content' => array( 'parts' => array( array( 'text' => $text ) ) ), ); } $url = sprintf( '%s/models/%s:batchEmbedContents?key=%s', self::ENDPOINT, rawurlencode( $model ), rawurlencode( $this->api_key ) ); $response = MYBOT_HTTP::post_json( $url, array( 'requests' => $requests ), array(), 15, 1 ); if ( is_wp_error( $response ) ) { return $response; } if ( empty( $response['embeddings'] ) || ! is_array( $response['embeddings'] ) ) { return new WP_Error( 'mybot_empty_embedding', __( 'Gemini returned no vectors.', 'aihouse' ) ); } $vectors = array(); /* * Keyed by position on purpose, and defensively by any index the response carries (see * MYBOT_LLM_OpenAI::embed): the indexer reads $vectors[ $position ] to know which chunk a * vector belongs to, so a reordered response must not be able to scramble that pairing. */ foreach ( $response['embeddings'] as $position => $item ) { if ( ! isset( $item['values'] ) || ! is_array( $item['values'] ) ) { continue; } $index = isset( $item['index'] ) ? (int) $item['index'] : (int) $position; // `$dropped` maps the numbering of the texts that were sent back to the caller's // positions, so a blank entry in the batch cannot shift the pairing. $index = isset( $dropped[ $index ] ) ? (int) $dropped[ $index ] : $index; $vectors[ $index ] = array_map( 'floatval', $item['values'] ); } ksort( $vectors ); return $vectors; } /** * Whether a model can read an image. See VISION_PREFIXES for how honest this answer is. * * @param string $model Model ID. * @return bool */ public function supports_vision( $model = '' ) { return MYBOT_LLM_Factory::model_matches( $model, self::VISION_PREFIXES, 'gemini', 'vision' ); } /** * Whether a model can read audio. False for every model here — see the interface docblock. * * @param string $model Model ID. * @return bool */ public function supports_audio( $model = '' ) { return false; } /** * Converts messages to the Gemini format. * * Gemini keeps the system instruction separate from the contents list. Content goes through * MYBOT_LLM_Content: a text message still becomes exactly one `text` part, as it did before 1.12.0, * while an image part becomes `inline_data`. * * @param array $messages Messages. * @return array{contents:array,system:string} */ protected function format_messages( $messages ) { $contents = array(); $system = ''; foreach ( (array) $messages as $message ) { if ( ! isset( $message['content'] ) ) { continue; } $role = isset( $message['role'] ) ? $message['role'] : 'user'; if ( 'system' === $role ) { $system .= ( '' === $system ? '' : "\n\n" ) . MYBOT_LLM_Content::text( $message['content'] ); continue; } $contents[] = array( 'role' => ( 'assistant' === $role ) ? 'model' : 'user', 'parts' => MYBOT_LLM_Content::to_gemini( $message['content'] ), ); } if ( empty( $contents ) ) { $contents[] = array( 'role' => 'user', 'parts' => array( array( 'text' => $system ) ), ); $system = ''; } return array( 'contents' => $contents, 'system' => $system, ); } }