'Bearer ' . $this->api_key, 'HTTP-Referer' => home_url( '/' ), 'X-Title' => 'AI House for WordPress', ); } /** * Provider ID. * * @return string */ public function get_id() { return 'openrouter'; } /** * Display name. * * @return string */ public function get_label() { return 'OpenRouter'; } /** * Default chat model. * * This is the free variant. Model lists change over time, so the admin offers a * button that loads the model list straight from OpenRouter. * * @return string */ public function get_default_chat_model() { return 'meta-llama/llama-3.3-70b-instruct' . self::FREE_SUFFIX; } /** * Sends the conversation, translating authentication failures into a usable hint. * * The admin sees this message on the Diagnostics screen, where "Missing Authentication * header" on its own reads like a plugin bug rather than "you pasted the wrong key". * * @param array $messages List of messages in role/content form. * @param array $args Arguments: model, temperature, max_tokens, timeout. * @return array|WP_Error */ public function chat( $messages, $args = array() ) { $result = parent::chat( $messages, $args ); if ( is_wp_error( $result ) ) { return new WP_Error( $result->get_error_code(), $this->explain_key_error( $result->get_error_message() ) ); } return $result; } /** * Default embedding model. * * @return string */ public function get_default_embedding_model() { return 'openai/text-embedding-3-small'; } /** * Vector dimensions of the default embedding model. * * @return int */ public function get_embedding_dimensions() { return 1536; } /** * Whether this model is a free variant. * * @param string $model Model ID. * @return bool */ public static function is_free_model( $model ) { return self::FREE_SUFFIX === substr( (string) $model, -strlen( self::FREE_SUFFIX ) ); } /** * Reads the free request budget left for the day. * * The result is cached for 5 minutes so no extra HTTP call is spent per message. * * @return array */ public function get_budget() { $cached = get_transient( self::BUDGET_TRANSIENT ); if ( is_array( $cached ) ) { return $cached; } $budget = array( 'known' => false, 'remaining' => null, 'limit' => null, 'used' => null, 'free_tier' => true, 'error' => '', ); $result = MYBOT_HTTP::get_json( $this->endpoint() . '/key', $this->auth_headers(), 8 ); if ( is_wp_error( $result ) ) { $budget['error'] = $result->get_error_message(); // When the budget cannot be read, let the request proceed; the circuit breaker covers the rest. set_transient( self::BUDGET_TRANSIENT, $budget, MINUTE_IN_SECONDS ); return $budget; } $data = ( isset( $result['data'] ) && is_array( $result['data'] ) ) ? $result['data'] : array(); $daily = ( isset( $data['free_model_daily_requests'] ) && is_array( $data['free_model_daily_requests'] ) ) ? $data['free_model_daily_requests'] : array(); if ( isset( $daily['limit'] ) ) { $budget['known'] = true; $budget['limit'] = (int) $daily['limit']; $budget['remaining'] = isset( $daily['remaining'] ) ? max( 0, (int) $daily['remaining'] ) : null; $budget['used'] = isset( $daily['used'] ) ? (int) $daily['used'] : null; } $budget['free_tier'] = ! empty( $data['is_free_tier'] ); set_transient( self::BUDGET_TRANSIENT, $budget, 5 * MINUTE_IN_SECONDS ); return $budget; } /** * Clears the budget cache, used after the admin clicks the check button. * * @return void */ public function flush_budget() { delete_transient( self::BUDGET_TRANSIENT ); } /** * Confirms that the API key is accepted. * * Deliberately NOT the model list: OpenRouter serves `/models` publicly, answering HTTP * 200 both with no `Authorization` header and with a wrong key. Verifying a credential * against it always "succeeds", which is exactly how a bad key was reported as saved. * `/key` requires authentication, so it is the only endpoint that can prove a key. * * @return true|WP_Error */ public function verify_credentials() { if ( '' === $this->api_key ) { return new WP_Error( 'mybot_missing_key', sprintf( /* translators: %s: provider name */ __( 'No API key configured for %s.', 'aihouse' ), $this->label() ) ); } $result = MYBOT_HTTP::get_json( $this->endpoint() . '/key', $this->auth_headers(), 12 ); if ( is_wp_error( $result ) ) { return new WP_Error( $result->get_error_code(), $this->explain_key_error( $result->get_error_message() ) ); } return true; } /** * Turns OpenRouter's authentication messages into something a site owner can act on. * * "Missing Authentication header" is returned both for an empty token and for any token * that is not in OpenRouter's own format — an OpenAI key, a placeholder copied from a * guide, or a key that picked up an invisible character on the way. On its own the * message gives no hint that the key is simply the wrong one, so the hint is added here. * * @param string $message Message from the API. * @return string */ protected function explain_key_error( $message ) { $mistyped = array( 'Missing Authentication header', 'No cookie auth credentials' ); $looks_wrong = false; foreach ( $mistyped as $needle ) { if ( false !== stripos( $message, $needle ) ) { $looks_wrong = true; break; } } if ( ! $looks_wrong ) { return $message; } return sprintf( /* translators: %s: message returned by OpenRouter */ __( 'OpenRouter did not recognise this key. OpenRouter keys start with "sk-or-v1-", so check that the key belongs to OpenRouter and not to another provider. The provider said: %s', 'aihouse' ), $message ); } /** * Fetches the model list from OpenRouter. * * The free and paid lists are disjoint: a model either costs nothing per prompt token or * it does not, so "free" plus "paid" adds up to "all". Keeping them separate is what makes * the two admin buttons show two different lists. * * Entries whose price is negative are dropped before either list is built. OpenRouter marks * its routers and meta-models — /auto, /auto-beta, /fusion, /pareto-code, /bodybuilder, * nvidia/switchyard, typesafe/jev-router — with `pricing.prompt = "-1"`, because they bill * whatever model they forward to rather than a rate of their own. A negative rate is not * "not free", so the paid filter used to keep them all, and the list an administrator is told * to pick a model from offered seven entries that are not models: measured 05/10/2026, they * sat at positions 46, 47, 49, 203, 311, 314 and 412 of 444. Three of the seven declare * `reasoning`, so choosing one brings back 6.17 — every question answered with the fallback * message. A router is also the one choice that cannot keep the promise this list exists to * make: the model that finally answers is picked per request, so the real-message test of * 1.5.7 proves nothing about the next question. * * @param string $filter One of 'all', 'free' or 'paid'. * @param bool $force Ignore the cache and ask OpenRouter again. * @return array|WP_Error */ public function list_models( $filter = 'free', $force = false ) { $filter = MYBOT_LLM_Factory::clean_model_filter( $filter ); $cache_key = MYBOT_LLM_Factory::models_cache_key( $this->get_id(), $filter ); if ( ! $force ) { $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } } $result = MYBOT_HTTP::get_json( $this->endpoint() . '/models', $this->auth_headers(), 12 ); if ( is_wp_error( $result ) ) { return $result; } $rows = ( isset( $result['data'] ) && is_array( $result['data'] ) ) ? $result['data'] : array(); $models = array(); foreach ( $rows as $row ) { if ( ! isset( $row['id'] ) ) { continue; } $id = (string) $row['id']; $pricing = ( isset( $row['pricing'] ) && is_array( $row['pricing'] ) ) ? $row['pricing'] : array(); /* * No price at all, and any negative price, means "this is not an ordinary model": * a router has no rate to compare and no fixed model to test. Both are skipped so * the list only ever offers something whose behaviour can be checked at pick time. */ if ( ! isset( $pricing['prompt'] ) || ! is_numeric( $pricing['prompt'] ) ) { continue; } $prompt_price = (float) $pricing['prompt']; if ( $prompt_price < 0 ) { continue; } $is_free = 0.0 === $prompt_price; if ( 'free' === $filter && ! $is_free ) { continue; } if ( 'paid' === $filter && $is_free ) { continue; } $models[] = array( 'id' => $id, 'name' => isset( $row['name'] ) ? (string) $row['name'] : $id, 'free' => $is_free, 'context' => isset( $row['context_length'] ) ? (int) $row['context_length'] : 0, ); } // Free models first, then by name. usort( $models, function ( $a, $b ) { if ( $a['free'] !== $b['free'] ) { return $a['free'] ? -1 : 1; } return strcasecmp( $a['name'], $b['name'] ); } ); set_transient( $cache_key, $models, 6 * HOUR_IN_SECONDS ); return $models; } }