WP_REST_Server::CREATABLE, 'callback' => array( $this, 'start_index' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'admin_permission' ), 'args' => array( 'force' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), ), ) ); register_rest_route( MYBOT_REST_NAMESPACE, '/index/status', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_status' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'admin_permission' ), ) ); register_rest_route( MYBOT_REST_NAMESPACE, '/index/reset', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'reset_index' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'admin_permission' ), ) ); register_rest_route( MYBOT_REST_NAMESPACE, '/test-connection', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'test_connection' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'admin_permission' ), ) ); register_rest_route( MYBOT_REST_NAMESPACE, '/test-lookup', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'test_lookup' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'admin_permission' ), 'args' => array( 'question' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field', ), ), ) ); register_rest_route( MYBOT_REST_NAMESPACE, '/models', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_models' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'admin_permission' ), 'args' => array( /* * No default on purpose. With 'default' => true, a caller that omitted the * parameter silently received the free list — which is exactly how "Load paid * models" ended up showing the same models as "Load free models". Callers must * now say which of the two disjoint lists they want. */ 'free' => array( 'required' => true, 'type' => 'boolean', 'sanitize_callback' => 'rest_sanitize_boolean', ), 'refresh' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), ), ) ); register_rest_route( MYBOT_REST_NAMESPACE, '/connect', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'connect' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'admin_permission' ), 'args' => array( /* * The provider is required rather than inferred from the saved settings: * this route exists precisely for the moment when the choice on screen has * not been saved yet, and falling back to the stored value would check the * wrong provider without saying so. */ 'provider' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_key', ), // Sent in the body, never in the query string: a key must not end up in a // URL, where it would be kept in server logs and browser history. 'api_key' => array( 'required' => false, 'type' => 'string', 'default' => '', ), 'free' => array( 'required' => true, 'type' => 'boolean', 'sanitize_callback' => 'rest_sanitize_boolean', ), /* * Optional, and only used to try the model the user just picked. It is never * saved here: Save stays the only thing that changes a setting. */ 'model' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); } /** * Loads the model list for the provider saved in the settings. * * The list changes over time, so it is fetched live and cached for six hours instead of * being hard-coded. * * @param WP_REST_Request $request The request. * @return WP_REST_Response|WP_Error */ public function get_models( $request ) { $settings = mybot()->settings; $provider = (string) $settings->get( 'llm_provider', 'openai' ); $client = MYBOT_LLM_Factory::make( $provider, $settings->provider_key( $provider ) ); if ( is_wp_error( $client ) ) { return $client; } $models = $client->list_models( $this->model_filter( $provider, (bool) $request->get_param( 'free' ) ), (bool) $request->get_param( 'refresh' ) ); if ( is_wp_error( $models ) ) { return $models; } return new WP_REST_Response( $this->models_payload( $client, $provider, $models, false, '' ), 200 ); } /** * Verifies an API key typed into the settings form, and remembers it when it works. * * This is what lets the model dropdown work before anything has been saved: the request * carries the provider and key currently on screen, so the check no longer depends on * what the database happens to hold. A key that the provider accepts is stored right * away, which is the "log in" half of the feature; the rest of the form is untouched * until the user presses Save. * * @param WP_REST_Request $request The request. * @return WP_REST_Response|WP_Error */ public function connect( $request ) { $settings = mybot()->settings; $provider = (string) $request->get_param( 'provider' ); $api_key = MYBOT_Settings::clean_api_key( (string) $request->get_param( 'api_key' ) ); if ( ! in_array( $provider, array_keys( MYBOT_LLM_Factory::options() ), true ) ) { return new WP_Error( 'mybot_unknown_provider', /* translators: %s: provider slug */ sprintf( __( 'Unsupported provider: %s', 'aihouse' ), $provider ), array( 'status' => 400 ) ); } // An empty field means "use the key already stored, or the one in wp-config.php". $key_for_call = ( '' === $api_key ) ? $settings->provider_key( $provider ) : $api_key; $client = MYBOT_LLM_Factory::make( $provider, $key_for_call ); if ( is_wp_error( $client ) ) { return $client; } /* * Prove the key BEFORE anything is stored, and prove it against an endpoint that * actually requires authentication. * * This check used to be the model list, which was wrong: OpenRouter publishes its * catalogue, answering HTTP 200 with no key and with a wrong key alike. So the key * was "verified" without ever being tested, stored, and reported to the user as * accepted — while every real call failed with 401. A key that has not been proven * is never written to the database now. */ $verified = $client->verify_credentials(); if ( is_wp_error( $verified ) ) { return $verified; } /* * The optional model is read before the list is fetched, for two reasons: the probe runs * whenever a model was named, and only the flow that *proves a key* has to bypass the model * cache. When the model was picked from a list that is already on screen, the list is not * needed again — returning the cached one keeps picking a model from costing two provider * round trips instead of one. */ $model = trim( (string) $request->get_param( 'model' ) ); $fresh = ( '' === $model ); $models = $client->list_models( $this->model_filter( $provider, (bool) $request->get_param( 'free' ) ), $fresh ); if ( is_wp_error( $models ) ) { return $models; } $saved = false; $masked = ''; if ( '' !== $api_key ) { $stored = $settings->store_provider_credential( $provider, $api_key ); if ( is_wp_error( $stored ) ) { return $stored; } $saved = true; $masked = MYBOT_Crypto::mask( $api_key ); } $payload = $this->models_payload( $client, $provider, $models, $saved, $masked ); // The user picked a model on screen, so try it before it is ever saved. if ( '' !== $model ) { $payload['model_check'] = $this->probe_model( $client, $model ); } return new WP_REST_Response( $payload, 200 ); } /** * Sends one short message to a chat model and reports what came back. * * A reasoning model thinks before it writes, so it can spend the whole token budget on its * reasoning field and return an empty `content`; when that model is saved, the chat answers * every question with the fallback message and no citation can ever appear. That trap has * already cost this project two sessions (docs/08 muc 6.17, 3.23), and the model's name does * not give it away — a real case was `dots-studio/dots-3-note-preview:free`, which matches no * obvious pattern. * * The one thing that does give it away is the reply itself, which is why this runs a real * message instead of reading the model list. It is deliberately cheap: one short question, a * small token ceiling. * * @param MYBOT_LLM_Provider $client Chat client of the provider on screen. * @param string $model Model ID to try. * @return array{status:string,message:string,detail:string,model:string} */ protected function probe_model( $client, $model ) { $result = $client->chat( array( array( 'role' => 'user', 'content' => 'Reply with the single word: OK', ), ), array( 'model' => $model, // Enough for a short answer, small enough that a reasoning model burns through it // quickly instead of running for a minute before saying nothing. 'max_tokens' => 48, 'timeout' => 15, ) ); if ( ! is_wp_error( $result ) ) { return array( 'status' => 'ok', 'message' => sprintf( /* translators: %s: model ID */ __( 'This model answered the test message. Press Save to keep it: %s', 'aihouse' ), $model ), 'detail' => '', 'model' => $model, ); } // The wording of an empty reply is matched only to pick the better message; anything // unrecognised still lands in 'failed', which is what it means. $reasoning = false !== strpos( $result->get_error_message(), 'reasoning' ); return array( 'status' => $reasoning ? 'reasoning' : 'failed', 'message' => $reasoning ? sprintf( /* translators: %s: model ID */ __( 'This model is a reasoning model: it spent the whole test budget thinking and wrote nothing. While it stays saved the chat answers every question with the fallback message, so no citation can appear. Pick a plain "instruct" or "chat" model instead: %s', 'aihouse' ), $model ) : sprintf( /* translators: 1: model ID, 2: error message */ __( 'The test message to %1$s did not succeed: %2$s', 'aihouse' ), $model, $result->get_error_message() ), 'detail' => $result->get_error_message(), 'model' => $model, ); } /** * Which of the provider's lists a request is asking for. * * Only OpenRouter splits its catalogue into free and paid. Everywhere else the flag is * ignored, so no caller can ask for a list that does not exist and be handed an empty * dropdown with no explanation. * * @param string $provider Provider ID. * @param bool $free_only Whether the caller asked for free models. * @return string One of 'all', 'free' or 'paid'. */ protected function model_filter( $provider, $free_only ) { if ( 'openrouter' !== $provider ) { return 'all'; } return $free_only ? 'free' : 'paid'; } /** * Response shared by both model routes. * * Keeping one builder means /models and /connect cannot drift apart and start reporting * different shapes to the same JavaScript. * * @param MYBOT_LLM_Provider $client Provider client. * @param string $provider Provider ID. * @param array $models Model list. * @param bool $saved Whether a freshly typed key was stored. * @param string $masked Masked form of the stored key, for the placeholder. * @return array */ protected function models_payload( $client, $provider, $models, $saved, $masked ) { $payload = array( 'success' => true, 'provider' => $provider, 'count' => count( $models ), 'models' => array_slice( $models, 0, 500 ), 'saved' => (bool) $saved, 'masked' => (string) $masked, ); // OpenRouter exposes the remaining free quota for the day. if ( method_exists( $client, 'get_budget' ) ) { $payload['budget'] = $client->get_budget(); } return $payload; } /** * Starts knowledge indexing. * * @param WP_REST_Request $request The request. * @return WP_REST_Response|WP_Error */ public function start_index( $request ) { $force = (bool) $request->get_param( 'force' ); $result = mybot()->indexer->start_full_index( $force ); if ( is_wp_error( $result ) ) { return $result; } return new WP_REST_Response( array( 'success' => true, 'message' => sprintf( /* translators: 1: number of items queued, 2: total items */ __( 'Queued %1$d of %2$d items. Background processing will continue.', 'aihouse' ), (int) $result['queued'], (int) $result['total'] ), 'queued' => (int) $result['queued'], 'skipped' => (int) $result['skipped'], 'total' => (int) $result['total'], 'progress' => $this->progress(), ), 200 ); } /** * Indexing progress, with the age of the stored vector check spelled out. * * The check is kept in an option and outlives the run that wrote it, so a box that prints it * without a date prints a green line that may describe an older run — and nothing on screen * says which (docs/08 muc 6.43). The age is computed here rather than in the indexer because * `human_time_diff()` is a display helper and belongs with the response, not with the state. * * @return array */ protected function progress() { $progress = mybot()->indexer->get_progress(); if ( ! isset( $progress['self_check'] ) || ! is_array( $progress['self_check'] ) ) { $progress['self_check'] = array(); } $progress['self_check']['age'] = ''; if ( ! empty( $progress['self_check']['at'] ) ) { $progress['self_check']['age'] = human_time_diff( (int) $progress['self_check']['at'], time() ); } return $progress; } /** * Knowledge indexing progress. * * @return WP_REST_Response */ public function get_status() { $plugin = mybot(); return new WP_REST_Response( array( 'success' => true, 'progress' => $this->progress(), 'queue' => $plugin->queue->stats(), 'circuit' => $plugin->circuit->summary(), 'failed_jobs' => $plugin->queue->recent_failures( 8 ), 'last_error' => $this->last_error(), 'last_lookup' => $this->last_lookup(), 'system' => $this->system_info(), ), 200 ); } /** * The most recent failure reason recorded when a fallback reply was served. * * @return array */ protected function last_error() { $stored = get_option( MYBOT_DEGRADED_OPTION, array() ); if ( ! is_array( $stored ) || empty( $stored['reason'] ) ) { return array(); } return array( 'reason' => (string) $stored['reason'], 'at' => isset( $stored['at'] ) ? (int) $stored['at'] : 0, ); } /** * What the knowledge base did on the last answered question. * * Recorded by the chat route, and rewritten by the lookup test, so the dashboard always * shows the freshest evidence instead of asking the reader to open the database. * * @return array */ protected function last_lookup() { $stored = get_option( MYBOT_RAG_TRACE_OPTION, array() ); if ( ! is_array( $stored ) || empty( $stored['question'] ) ) { return array(); } $stored['hint'] = MYBOT_Retriever::describe( $stored ); return $stored; } /** * Environment information, used by the diagnostics view. * * @return array */ protected function system_info() { $settings = mybot()->settings; return array( 'pluginVersion' => MYBOT_VERSION, 'dbVersion' => (string) get_option( MYBOT_DB_VERSION_OPTION, '' ), 'wpVersion' => get_bloginfo( 'version' ), 'phpVersion' => PHP_VERSION, 'crypto' => MYBOT_Crypto::is_available(), 'objectCache' => (bool) wp_using_ext_object_cache(), 'multisite' => is_multisite(), 'asyncLogging' => (bool) $settings->get( 'async_logging', 1 ), 'llmProvider' => (string) $settings->get( 'llm_provider', '' ), 'llmModel' => (string) $settings->get( 'llm_model', '' ), 'vectorStore' => (string) $settings->get( 'vector_store', 'none' ), 'ragAvailable' => $settings->rag_available(), 'languages' => mybot()->languages->enabled(), 'defaultLang' => mybot()->languages->default_code(), 'cacheTtl' => (int) $settings->get( 'cache_ttl', 0 ), 'rateLimit' => (int) $settings->get( 'rate_limit', 0 ), 'rateWindow' => (int) $settings->get( 'rate_window', 60 ), ); } /** * Clears the indexing fingerprint so everything is indexed again from scratch. * * @return WP_REST_Response */ public function reset_index() { $deleted = mybot()->indexer->reset_manifest(); delete_option( MYBOT_INDEX_STATE_OPTION ); return new WP_REST_Response( array( 'success' => true, 'message' => sprintf( /* translators: %d: number of items whose fingerprint was cleared */ __( 'Cleared the indexing fingerprint for %d items.', 'aihouse' ), (int) $deleted ), 'deleted' => (int) $deleted, ), 200 ); } /** * Tests the connection to the LLM, the embedding provider and the vector store. * * @return WP_REST_Response */ public function test_connection() { $plugin = mybot(); $settings = $plugin->settings; $report = array( 'llm' => array( 'ok' => false, 'message' => '', ), 'embedding' => array( 'ok' => false, 'message' => '', ), 'vector' => array( 'ok' => false, 'message' => '', ), ); $provider = MYBOT_LLM_Factory::chat_provider( $settings ); if ( is_wp_error( $provider ) ) { $report['llm']['message'] = $provider->get_error_message(); } else { $result = $provider->chat( array( array( 'role' => 'system', 'content' => 'Answer with exactly one word: OK', ), array( 'role' => 'user', 'content' => 'Connection test.', ), ), array( 'model' => (string) $settings->get( 'llm_model' ), /* * 64 rather than 16: a reasoning model spends its budget on the reasoning * field before it writes anything, so a small ceiling made a working key * look broken ("returned an empty reply") while the chat itself was fine. */ 'max_tokens' => 64, 'timeout' => 10, ) ); if ( is_wp_error( $result ) ) { $report['llm']['message'] = $result->get_error_message(); } else { $report['llm']['ok'] = true; $report['llm']['message'] = __( 'LLM connection succeeded.', 'aihouse' ); } } /* * What the chosen model can read (1.12.0). * * This line is the first consumer of the capability gate, and it exists for a reason that is * about to matter: an attachment button may only be offered when the model can actually read * what it would send. `/chat` accepts text only today, so the honest answer today is about the * MODEL, not about a feature — and the wording says "on the list", because that list is kept by * hand in each provider class rather than measured from the provider (see * `MYBOT_LLM_Provider::supports_vision()`). */ if ( ! is_wp_error( $provider ) ) { $model = (string) $settings->get( 'llm_model' ); $sees_pictures = MYBOT_LLM_Factory::can( $provider, 'vision', $model ); $report['vision'] = array( 'ok' => $sees_pictures, 'message' => $sees_pictures ? sprintf( /* translators: %s: model ID */ __( '%s is on the list of models that can read an image.', 'aihouse' ), $model ) : sprintf( /* translators: %s: model ID */ __( '%s is not on the list of models that can read an image, so no picture would be sent to it.', 'aihouse' ), $model ), ); } // For OpenRouter, also include the remaining free quota for the day. if ( method_exists( $provider, 'get_budget' ) ) { $provider->flush_budget(); $budget = $provider->get_budget(); if ( ! empty( $budget['known'] ) ) { $report['budget'] = array( 'ok' => ( $budget['remaining'] > 0 ), 'message' => sprintf( /* translators: 1: remaining, 2: daily limit */ __( 'Free quota today: %1$s of %2$s requests left.', 'aihouse' ), number_format_i18n( (int) $budget['remaining'] ), number_format_i18n( (int) $budget['limit'] ) ), ); } elseif ( '' !== $budget['error'] ) { $report['budget'] = array( 'ok' => false, 'message' => $budget['error'], ); } } /* * The embedding provider gets its own line, and it is the newest of the three on purpose. * * The check above proves the CHAT key; this one proves the key that creates vectors. They are * not the same key, and until 1.6.7 nothing on this screen tested the second one: * MYBOT_Settings::embedding_key() prefers a separate `embedding_api_key` and only falls back * to the provider key, so an expired value there produced a fully green Test connection and * an indexing run that died with "API key expired." — measured on a real site on 06/10/2026, * green at 20:33 for a failure that had happened at 14:27 (docs/08 muc 3.37(i)). * * A feature whose only failure signal is "the knowledge base is missing some posts" is the * silent-failure shape of 3.28, so it is asked here, in one small call, on the screen people * press when something looks wrong. */ $report['embedding'] = $this->test_embedding( $settings ); $vector = MYBOT_Vector_Factory::test_connection( $settings ); if ( is_wp_error( $vector ) ) { $report['vector']['message'] = $vector->get_error_message(); } else { $report['vector']['ok'] = true; $report['vector']['message'] = __( 'Vector store connection succeeded.', 'aihouse' ); } /* * The conversation-log mirror gets its own line, and only when the administrator asked for * it. Until 1.6.0 this feature had no way to be tested: the first proof it was broken was * an empty table in Supabase, days later, with nothing on any screen to explain it (3.28). */ $mybot_mirror = MYBOT_Supabase_Log::state(); if ( ! empty( $mybot_mirror['wanted'] ) ) { $probe = MYBOT_Supabase_Log::probe(); $report['log_mirror'] = array( 'ok' => ! is_wp_error( $probe ), 'message' => is_wp_error( $probe ) ? $probe->get_error_message() : __( 'The log mirror wrote a probe row into public.mybot_messages and removed it again, so conversations will be copied.', 'aihouse' ), ); } /* The request mirror is a different table and a different decision, so it gets its own line (1.22.8). */ $mybot_requests_mirror = MYBOT_Supabase_Requests::state(); if ( ! empty( $mybot_requests_mirror['wanted'] ) ) { $requests_probe = MYBOT_Supabase_Requests::probe(); $report['requests_mirror'] = array( 'ok' => ! is_wp_error( $requests_probe ), 'message' => is_wp_error( $requests_probe ) ? $requests_probe->get_error_message() : __( 'The request mirror wrote a probe row into public.mybot_requests and removed it again, so customer requests will be copied.', 'aihouse' ), ); } $report['settings'] = array( 'ok' => true, 'message' => $this->settings_summary( $settings ), ); return new WP_REST_Response( array( 'success' => true, 'report' => $report, ), 200 ); } /** * Proves the embedding key by asking for one real vector. * * One short string, one call, and the reply either contains a vector or explains itself. The * dimension count is reported because it is the number that has to match the vector column in * the database: a working key with the wrong model still produces vectors, just vectors the * store cannot compare against the ones already in it. * * Never throws: this is a diagnostic, so a failure becomes a line on the screen. * * @param MYBOT_Settings $settings Settings. * @return array{ok: bool, message: string} */ protected function test_embedding( $settings ) { if ( ! $settings->rag_available() ) { return array( 'ok' => false, 'message' => __( 'RAG is off, or the embedding and vector store keys are not fully configured, so no vector can be created yet.', 'aihouse' ), ); } $embedder = MYBOT_LLM_Factory::embedding_provider( $settings ); if ( is_wp_error( $embedder ) ) { return array( 'ok' => false, 'message' => $embedder->get_error_message(), ); } $model = $settings->embedding_model(); $vectors = $embedder->embed( array( 'mybot embedding connection test' ), $model ); if ( is_wp_error( $vectors ) ) { return array( 'ok' => false, 'message' => $vectors->get_error_message(), ); } $vector = ( is_array( $vectors ) && isset( $vectors[0] ) && is_array( $vectors[0] ) ) ? $vectors[0] : array(); if ( empty( $vector ) ) { return array( 'ok' => false, 'message' => sprintf( /* translators: %s: embedding model ID */ __( 'The embedding provider answered with no vector for %s, so indexing cannot store anything.', 'aihouse' ), $model ), ); } return array( 'ok' => true, 'message' => sprintf( /* translators: 1: embedding model ID, 2: number of dimensions returned */ __( 'Embedding connection succeeded: %1$s returned %2$d dimensions.', 'aihouse' ), $model, count( $vector ) ), ); } /** * Runs a real knowledge base lookup for a question the administrator types. * * "Test connection" proves the keys and "Index knowledge" proves the writes; nothing until * now proved the read that produces citations, which is why a reply without sources could * be blamed on three different things at once. This runs the same code path the chat runs, * and reports the numbers that separate those three cases: * * - the store returned nothing at all -> the table looks empty, index the knowledge; * - the closest chunk scored under the threshold -> lower Minimum score; * - the call failed -> the embedding or the RPC is broken, and the message says which. * * The lookup runs even when the chat would have skipped it, because the point is to prove * the pipeline rather than to agree with the heuristic. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function test_lookup( $request ) { $plugin = mybot(); $retriever = $plugin->retriever; $question = trim( (string) $request->get_param( 'question' ) ); if ( '' === $question ) { return new WP_Error( 'mybot_lookup_question_missing', __( 'Type a question to look up.', 'aihouse' ), array( 'status' => 400 ) ); } // Ask the heuristic first so the report can say whether the chat itself would search. $would_use = $retriever->should_use( $question, 'auto' ); $chunks = $retriever->retrieve( $question ); $lookup = $retriever->trace( array( 'question' => MYBOT_Retriever::shorten( $question ), 'used' => $would_use, 'flow' => $would_use ? 'deep' : 'quick', 'sources' => is_wp_error( $chunks ) ? array() : $retriever->build_sources( $chunks ), ) ); if ( ! is_wp_error( $chunks ) && empty( $chunks ) ) { // Measure with the threshold removed: see MYBOT_Retriever::retrieve_with(). $probe = $retriever->retrieve_with( $question, 0.0, (int) $lookup['top_k'] ); $lookup['best_score'] = is_wp_error( $probe ) ? null : MYBOT_Retriever::best_score( $probe ); $lookup['rows'] = is_wp_error( $probe ) ? 0 : count( $probe ); /* * Show what the store considers closest even though nothing cleared the bar. Seeing * the title of a 0.06 chunk tells the reader at once whether the topic is in the * knowledge base at all, which the score alone cannot. */ $lookup['nearest'] = is_wp_error( $probe ) ? array() : array_slice( $retriever->build_sources( $probe ), 0, 3 ); /* * And the decisive check: a chunk that is already stored must find itself. If it * cannot, the vectors were built with another embedding model and the threshold is * the wrong thing to touch. */ if ( ! is_wp_error( $probe ) && ! empty( $probe[0]['content'] ) ) { $lookup['roundtrip'] = $retriever->roundtrip( (string) $probe[0]['content'], isset( $probe[0]['id'] ) ? (string) $probe[0]['id'] : '' ); } } else { $lookup['best_score'] = isset( $lookup['top_score'] ) ? $lookup['top_score'] : null; $lookup['rows'] = isset( $lookup['matched'] ) ? (int) $lookup['matched'] : 0; } // Plain diagnostic line, like the one Test connection prints: the numbers a reader needs // to compare this run with the settings that produced it. $lookup['settings'] = sprintf( 'question="%1$s" · embedding=%2$s · dims=%3$s · min_score=%4$s · top_k=%5$d', (string) $lookup['question'], isset( $lookup['model'] ) ? (string) $lookup['model'] : '—', isset( $lookup['dims'] ) ? (int) $lookup['dims'] : 0, MYBOT_Retriever::format_score( $lookup['min_score'] ), (int) $lookup['top_k'] ); $lookup['hint'] = MYBOT_Retriever::describe( $lookup ); // Refreshed after the probe: trace() could not know the numbers added above. $lookup['state'] = MYBOT_Retriever::state( $lookup ); // Keep the same record the dashboard reads, so the test doubles as the last lookup. update_option( MYBOT_RAG_TRACE_OPTION, $lookup, false ); return new WP_REST_Response( array( 'success' => true, 'lookup' => $lookup, ), 200 ); } /** * One-line summary of the settings the connection test actually used. * * The test reads the settings saved in the database, never the form on screen, so printing * them turns "The vector store is not enabled." from a puzzle into a statement: the saved * vector_store is none. * * The embedding model is printed as "model via provider" rather than "provider/model": the * model ID already contains a slash of its own ("openai/text-embedding-3-small"), so joining * the two with a slash produced "openrouter/openai/text-embedding-3-small" and read like a * doubled prefix — a reader concluded the model was misconfigured when it was not. * * @param MYBOT_Settings $settings Settings. * @return string */ protected function settings_summary( $settings ) { return sprintf( 'provider=%1$s · model=%2$s · embeddings=%4$s via %3$s · vector_store=%5$s · top_k=%6$d · min_score=%7$s', (string) $settings->get( 'llm_provider', '' ), (string) $settings->get( 'llm_model', '' ), (string) $settings->get( 'embedding_provider', '' ), (string) $settings->embedding_model(), (string) $settings->get( 'vector_store', 'none' ), (int) $settings->get( 'rag_top_k', 4 ), MYBOT_Retriever::format_score( $settings->get( 'rag_min_score', 0.35 ) ) ); } }