WP_REST_Server::CREATABLE, 'callback' => array( $this, 'handle_chat' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'public_permission' ), 'args' => array( 'message' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field', 'validate_callback' => array( $this, 'validate_message' ), ), /* * The picture, as a data URI (1.14.0). Deliberately NOT run through a text sanitiser: * `sanitize_text_field()` strips the base64 padding and every `+` and `/` in it, * turning a valid picture into rubbish that then fails a decode three steps later * with a message about the wrong thing. `MYBOT_Attachments::store()` is the * validator, and it asks the BYTES what they are rather than the label. */ 'image' => array( 'required' => false, 'type' => 'string', 'default' => '', ), 'session_id' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), 'mode' => array( 'required' => false, 'type' => 'string', 'default' => 'auto', 'sanitize_callback' => 'sanitize_key', 'validate_callback' => function ( $value ) { return in_array( $value, array( 'auto', 'quick', 'deep' ), true ); }, ), 'lang' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_key', ), ), ) ); register_rest_route( MYBOT_REST_NAMESPACE, '/feedback', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'handle_feedback' ), 'permission_callback' => array( 'MYBOT_REST_Controller', 'public_permission' ), 'args' => array( 'session_id' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'rating' => array( 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', ), ), ) ); } /** * Validates the message content. * * @param string $value Value. * @return true|WP_Error */ public function validate_message( $value ) { $length = MYBOT_Chunker::length( trim( (string) $value ) ); if ( $length < 1 ) { return new WP_Error( 'mybot_empty_message', __( 'The message cannot be empty.', 'aihouse' ), array( 'status' => 400 ) ); } if ( $length > 2000 ) { return new WP_Error( 'mybot_message_too_long', __( 'The message is too long — 2000 characters maximum.', 'aihouse' ), array( 'status' => 400 ) ); } return true; } /** * Handles a single question. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function handle_chat( $request ) { $started = microtime( true ); $plugin = mybot(); $settings = $plugin->settings; // 1. Rate limit. $limit = $plugin->security->enforce_rate_limit(); if ( is_wp_error( $limit ) ) { return $limit; } $message = trim( (string) $request->get_param( 'message' ) ); $session_id = $plugin->security->clean_session_id( (string) $request->get_param( 'session_id' ) ); if ( '' === $session_id ) { $session_id = $plugin->security->new_session_id(); } $requested_mode = (string) $request->get_param( 'mode' ); $lang = $plugin->languages->resolve( (string) $request->get_param( 'lang' ) ); /* * 1b. A picture, if the visitor attached one (1.14.0). * * Three things happen here, in this order, and the order is the design: * * 1. **The gate.** A model that cannot read an image must not be sent one: the request would * fail at the provider, in English, after the visitor had already been charged for it — and * the widget hides the button in that case anyway, so reaching here means a hand-made * request. `MYBOT_LLM_Factory::can()` answers false when it cannot be asked (docs/08 muc 3.65). * 2. **Storage**, before anything is sent anywhere. A picture that reached the model but was * never stored would leave an answer about a photo nobody can look at again. * 3. The record is carried in `$attachment` and travels into the log row, so the conversation * keeps the fact that this question arrived with a picture. */ $attachment = array(); $image_uri = trim( (string) $request->get_param( 'image' ) ); if ( '' !== $image_uri ) { $provider = MYBOT_LLM_Factory::chat_provider( $settings ); if ( is_wp_error( $provider ) ) { return $provider; } if ( ! MYBOT_LLM_Factory::can( $provider, 'vision', (string) $settings->get( 'llm_model' ) ) ) { return new WP_Error( 'mybot_vision_unsupported', __( 'The model configured for this site cannot read pictures, so this one was not sent.', 'aihouse' ), array( 'status' => 400 ) ); } $stored = MYBOT_Attachments::store( $image_uri ); if ( is_wp_error( $stored ) ) { $stored->add_data( array( 'status' => 400 ) ); return $stored; } $attachment = $stored; } /* * The visitor's own words outrank the language switcher. * * The switcher is a setting somebody chose once, possibly on an earlier visit; the message is * evidence of what they are actually writing now. On a Vietnamese site whose widget sat on EN, * every Vietnamese question used to come back in English — correct, cited and useless to the * person reading it (docs/08 muc 6.35). * * `detect()` only speaks when the evidence is decisive, and this block additionally requires * the language to be one the site has enabled. `$lang` is decided BEFORE the cache key below * on purpose: the reply's language is part of what is being cached, and it also goes into the * log, the trace and the response the widget reads. */ $detected = apply_filters( 'mybot_message_language', $plugin->languages->detect( $message ), $message, $lang ); if ( is_string( $detected ) && '' !== $detected && $detected !== $lang && $plugin->languages->is_enabled( $detected ) ) { $lang = sanitize_key( $detected ); } // 2. Decide the flow. $use_rag = in_array( $requested_mode, array( 'auto', 'deep' ), true ) && $plugin->retriever->should_use( $message, 'deep' === $requested_mode ? 'always' : 'auto' ); /* * The knowledge lock is stronger than the widget's mode. "Quick only" and "never" are * choices about a page, and the lock is a choice about the whole site made by the owner in a * file only they can reach — so it wins, and it wins even when the requested mode was * `quick`. The second call is also what puts the lock's own reason in the trace. */ if ( class_exists( 'MYBOT_Knowledge_Lock' ) && MYBOT_Knowledge_Lock::is_active() ) { $use_rag = $plugin->retriever->should_use( $message, 'always' ); } $mode = $use_rag ? 'deep' : 'quick'; $cached = false; // Set here so every later read is defined, whichever branch runs. $needs_human = false; // 3. Reply cache. The language must be part of the key, otherwise a visitor who // switches language would receive the reply generated for the previous language. $cache_key = MYBOT_Cache::key( MYBOT_Cache::normalize( $message ), array( $mode, $lang, $settings->get( 'llm_provider' ), $settings->get( 'llm_model' ), /* * The picture is part of the key, and it has to be: the same words with a different * photo are a different question ("what is wrong here?"), and without this the second * visitor would be handed the first one's answer — about a picture the model never saw. */ empty( $attachment ) ? '' : md5( $image_uri ), ) ); $cached_reply = $plugin->cache->get( $cache_key ); if ( is_string( $cached_reply ) && '' !== $cached_reply ) { $cached = true; /* * 1.5.3 stores the sources beside the reply. Entries written before that hold the * reply on its own, and throwing the sources away meant a repeated question lost * every citation while still looking like an ordinary answer. * * `needs_human` is stored for the same reason: without it, asking the same * unanswerable question twice showed the contact form once and then silently * stopped offering it. */ $decoded = json_decode( $cached_reply, true ); if ( is_array( $decoded ) && isset( $decoded['reply'] ) ) { $reply = (string) $decoded['reply']; $sources = ( isset( $decoded['sources'] ) && is_array( $decoded['sources'] ) ) ? $decoded['sources'] : array(); $needs_human = ! empty( $decoded['needs_human'] ); } else { $reply = $cached_reply; $sources = array(); $needs_human = false; } } else { $generated = $this->generate( $message, $session_id, $mode, $use_rag, $lang, $attachment ); if ( is_wp_error( $generated ) ) { return $generated; } $generated = self::filter_reply( $generated, $message, $session_id, $lang, $use_rag ); $reply = $generated['reply']; $sources = $generated['sources']; $degraded = $generated['degraded']; $matched = (int) $generated['matched']; $marker_said_no = ! empty( $generated['marker'] ); /* * Two different failures, one outcome. * * The model says it cannot answer (marker), or the knowledge base itself came back * with nothing to work from (`matched` is zero). Either way the visitor is about to * read "I don't have that information", which is exactly the moment to offer a human * instead of ending the conversation. * * The second check only applies to the deep flow: the quick flow never searches, so a * zero there means nothing at all. */ if ( empty( $degraded ) && ( $marker_said_no || ( $use_rag && 0 === $matched && empty( $generated['small_talk'] ) ) ) ) { $needs_human = true; } /* * And the case the two checks above miss: a visitor who ASKS for a person. * * The answer to "tôi muốn gặp người hỗ trợ" is usually a good one — the knowledge base answers it, so * neither check fires and the hand-over form never appeared. Asking for a human is not a failure to * answer; it is a request, and it wins regardless of how good the answer was (1.22.2). */ if ( MYBOT_Human_Intent::wants_human( $message ) ) { $needs_human = true; } } // Store the reply, its sources and whether a human is needed, so a repeated question // keeps offering the same thing. Writing the cache before the trace below matters: // record_trace() rebuilds the retriever trace from the last call. if ( empty( $degraded ) ) { $plugin->cache->set( $cache_key, (string) wp_json_encode( array( 'reply' => $reply, 'sources' => $sources, 'needs_human' => ! empty( $needs_human ), ) ), (int) $settings->get( 'cache_ttl', 3600 ) ); } $latency = (int) round( ( microtime( true ) - $started ) * 1000 ); /* * Record what the knowledge base did, so that a reply without citations has an * explanation waiting on the dashboard instead of sending the reader into phpMyAdmin. * record_trace() skips the write when nothing changed, so a repeated question served * from the cache does not cost an option write every time. A fallback reply is left * out on purpose: it is not the knowledge base that failed, and it already has its own * record. */ if ( empty( $degraded ) ) { $this->record_trace( $plugin->retriever->trace( array( 'question' => MYBOT_Retriever::shorten( $message ), 'flow' => $mode, 'cached' => $cached, 'sources' => $sources, ) ) ); } // 4. Logging: push to the queue, no immediate database write. $plugin->logger->log( array( 'session_id' => $session_id, 'role' => 'user', 'content' => $message, 'attachments' => $attachment, 'lang' => $lang, 'mode' => $mode, ) ); $plugin->logger->log( array( 'session_id' => $session_id, 'role' => 'bot', 'content' => $reply, 'lang' => $lang, 'mode' => $mode, 'provider' => (string) $settings->get( 'llm_provider' ), 'model' => (string) $settings->get( 'llm_model' ), 'latency_ms' => $latency, 'cache_hit' => $cached ? 1 : 0, ) ); return new WP_REST_Response( array( 'success' => true, 'session_id' => $session_id, 'reply' => $reply, 'mode' => $mode, 'lang' => $lang, 'cached' => $cached, 'degraded' => isset( $degraded ) ? (bool) $degraded : false, 'sources' => $sources, 'needs_human' => ! empty( $needs_human ), 'latency_ms' => $latency, ), 200 ); } /** * Stores the knowledge base trace for the dashboard, but only when it changed. * * An option write on every answered question would undo the point of asynchronous logging, * and a question served from the cache produces exactly the same trace as the answer it was * copied from. Only the fields a reader acts on are compared. * * @param array $trace Trace. * @return void */ protected function record_trace( $trace ) { $signature = array( 'used', 'reason', 'error', 'chunks', 'matched', 'top_score', 'best_score', 'min_score', 'question', 'cached', 'sources' ); $previous = get_option( MYBOT_RAG_TRACE_OPTION, array() ); $previous = is_array( $previous ) ? $previous : array(); foreach ( $signature as $key ) { $now = isset( $trace[ $key ] ) ? $trace[ $key ] : null; $then = isset( $previous[ $key ] ) ? $previous[ $key ] : null; if ( $now !== $then ) { update_option( MYBOT_RAG_TRACE_OPTION, $trace, false ); return; } } } /** * Let an add-on replace the reply — the seam that makes a deterministic answer possible (1.22.9). * * WHY THIS EXISTS * * Some answers are not opinions: a warranty expiry date, a stock count, an invoice status. An add-on that KNOWS the * answer should not have to persuade a model to repeat it. Until this filter there was no way to answer without the * model at all: `mybot_llm_messages` shapes the REQUEST, and nothing shaped the REPLY. The warranty add-on measured * the cost of that gap on a real site — its instruction block reached the model (the add-on's own diagnostic counted * 1694 characters added, four times) and the reply still said *"I can't check warranty information using phone * numbers"*, because one sentence in this plugin's prompt outranked the facts. * * THE CONTRACT * * in array `$generated` with `reply`, `sources`, `degraded`, `marker`, `matched`, `small_talk` * out the same shape, with a different `reply` (and `sources` if the site can cite something) * * A filter that hands back anything that is not an array — or an array missing the four keys the caller reads — is * **ignored**, not trusted. A half-finished add-on must not be able to blank the chat for a whole site; that is the * same rule as `docs/13` mục 5b: "the feature is not there", never "the site is down". * * `matched` stays the add-on's to set, because the caller uses it to decide whether to offer the hand-over form. * * COST WHEN UNUSED: one `apply_filters` call. A site with no add-on gets a reply byte-for-byte identical to 1.22.8 — * which is why this ships as a minor release. * * @param array $generated Reply data from `generate()`. * @param string $message The visitor's message. * @param string $session_id Session ID. * @param string $lang Language code. * @param bool $use_rag Whether the knowledge base was searched for this reply. * @return array */ public static function filter_reply( array $generated, $message, $session_id, $lang, $use_rag ) { /** * Filters the reply before it is cached, logged and returned. * * @param array $generated Reply data. * @param string $message The visitor's message. * @param string $session_id Session ID. * @param string $lang Language code. * @param bool $use_rag Whether the knowledge base was searched for this reply. */ $filtered = apply_filters( 'mybot_chat_reply', $generated, $message, $session_id, $lang, $use_rag ); if ( ! is_array( $filtered ) ) { return $generated; } foreach ( array( 'reply', 'sources', 'degraded', 'matched' ) as $key ) { if ( ! array_key_exists( $key, $filtered ) ) { return $generated; } } return $filtered; } /** * Generates the reply from the LLM, with error handling and a circuit breaker. * * @param string $message Question. * @param string $session_id Session ID. * @param string $mode Selected flow. * @param bool $use_rag Whether RAG is used. * @param string $lang Normalized language code. * @param array $attachment Stored attachment record, or array() (1.14.0). * @return array|WP_Error */ protected function generate( $message, $session_id, $mode, $use_rag, $lang, $attachment = array() ) { $plugin = mybot(); $settings = $plugin->settings; $locked = class_exists( 'MYBOT_Knowledge_Lock' ) && MYBOT_Knowledge_Lock::is_active(); $small_talk = false; /* * The lock, when the knowledge base cannot be searched at all: there is nothing to answer * from, and answering from the model's own knowledge is the one thing the lock forbids. This * returns before a provider is resolved and before a single token is spent. * * The exception is the short greeting the owner chose to keep answering (docs/08 muc * 6.45(d)). It is the only path where the lock still calls the model with no website content * at all, and it carries a note that permits a greeting and forbids one fact. */ if ( $locked && ! $use_rag && ! MYBOT_Knowledge_Lock::is_small_talk( $message ) ) { return $this->locked_response( $lang ); } $provider = MYBOT_LLM_Factory::chat_provider( $settings ); if ( is_wp_error( $provider ) ) { return $this->degraded_response( $provider->get_error_message(), $lang ); } $provider_id = $provider->get_id(); // When the circuit breaker is open, return the fallback reply immediately without calling the network. if ( $plugin->circuit->is_open( $provider_id ) ) { return $this->degraded_response( __( 'The AI provider is paused after repeated failures.', 'aihouse' ), $lang ); } // Free budget: when the daily quota is used up, return the fallback reply right away // instead of making a call, hitting a 429 and holding a worker for nothing. $budget_error = $this->check_budget( $provider ); if ( is_wp_error( $budget_error ) ) { return $this->degraded_response( $budget_error->get_error_message(), $lang ); } $context = ''; $sources = array(); $matched = 0; if ( $use_rag ) { $chunks = $plugin->retriever->retrieve( $message ); if ( is_wp_error( $chunks ) ) { $plugin->circuit->record_failure( 'embedding', (int) $settings->get( 'circuit_failures', 5 ), (int) $settings->get( 'circuit_cooldown', 120 ) ); // A RAG failure should not block the reply: fall back to the quick flow. $mode = 'quick'; $context = ''; } else { $context = $plugin->retriever->build_context( $chunks ); $sources = $plugin->retriever->build_sources( $chunks ); $matched = count( $chunks ); } } /* * The lock, after a search that found nothing above the score floor. This is the second of * the two token leaks in docs/08 muc 6.45, and the reason the lock exists at all: the old * code called the model with an EMPTY context — no data, and (because `build_messages()` * only adds the "answer only from this" note when there IS a context) no instruction either * — which is a general-knowledge answer paid for by the owner. * * Refusing costs nothing, and the visitor still gets the hand-over form, because the caller * reads `matched = 0` as "the bot could not answer". */ if ( $locked && 0 === $matched ) { if ( ! MYBOT_Knowledge_Lock::is_small_talk( $message ) ) { return $this->locked_response( $lang ); } $small_talk = true; } $messages = $this->build_messages( $message, $session_id, $context, $lang, $small_talk, $attachment ); $result = $provider->chat( $messages, array( 'model' => (string) $settings->get( 'llm_model', $provider->get_default_chat_model() ), 'temperature' => (float) $settings->get( 'llm_temperature', 0.3 ), 'max_tokens' => (int) $settings->get( 'llm_max_tokens', 500 ), 'timeout' => (int) $settings->get( 'llm_timeout', 8 ), ) ); if ( is_wp_error( $result ) ) { $opened = $plugin->circuit->record_failure( $provider_id, (int) $settings->get( 'circuit_failures', 5 ), (int) $settings->get( 'circuit_cooldown', 120 ) ); $reason = $result->get_error_message(); if ( $opened ) { $reason .= ' ' . __( 'The circuit breaker opened to protect the server.', 'aihouse' ); } return $this->degraded_response( $reason, $lang ); } $plugin->circuit->record_success( $provider_id ); // Strip the marker before the reply is cached, logged or shown: a visitor must never see // it, and a reply that kept it would be cached with it and look broken on the second ask. $reply = (string) $result['content']; $marker = false !== strpos( $reply, self::NO_ANSWER_MARKER ); if ( $marker ) { $reply = trim( str_replace( self::NO_ANSWER_MARKER, '', $reply ) ); } return array( 'reply' => $reply, 'sources' => $sources, 'degraded' => false, 'marker' => $marker, 'matched' => $matched, 'small_talk' => $small_talk, ); } /** * The reply the knowledge lock gives when the website has nothing to answer with. * * Deliberately NOT a degraded reply: nothing failed. `degraded` is what tells the caller to skip * the cache and to leave the trace alone, and a refusal is neither — it is the answer the site * was configured to give, it may be cached (which makes the second identical question cost * nothing at all), and the trace is where the owner sees the lock doing its job. * * `matched` stays 0 so the caller offers the hand-over form, which is the useful ending for a * visitor whose question this website cannot answer. * * @param string $lang Normalized language code. * @return array */ protected function locked_response( $lang ) { return array( 'reply' => MYBOT_Languages::locked_refusal( $lang ), 'sources' => array(), 'degraded' => false, 'marker' => false, 'matched' => 0, 'locked' => true, 'small_talk' => false, ); } /** * Checks the provider's free budget, when the provider exposes one. * * OpenRouter limits the ":free" variants to 20 requests per minute and 50 requests * per day for accounts that have never been credited. Knowing this in advance beats letting a visitor hit a 429. * * @param MYBOT_LLM_Provider $provider Provider. * @return true|WP_Error */ protected function check_budget( $provider ) { if ( ! method_exists( $provider, 'get_budget' ) ) { return true; } $budget = $provider->get_budget(); if ( empty( $budget['known'] ) || null === $budget['remaining'] ) { return true; } if ( $budget['remaining'] > 0 ) { return true; } return new WP_Error( 'mybot_budget_exhausted', sprintf( /* translators: 1: requests used, 2: daily limit */ __( 'The free daily quota is used up (%1$s/%2$s requests). It resets on the UTC day boundary.', 'aihouse' ), number_format_i18n( (int) $budget['used'] ), number_format_i18n( (int) $budget['limit'] ) ) ); } /** * Builds the message array sent to the LLM. * * @param string $message New question. * @param string $session_id Session ID. * @param string $context RAG context. * @param string $lang Language code. * @param bool $small_talk Whether the knowledge lock is letting this message through as a * greeting, with no website content behind it. * @param array $attachment Stored attachment record, or array() (1.14.0). * @return array */ protected function build_messages( $message, $session_id, $context, $lang, $small_talk = false, $attachment = array() ) { $plugin = mybot(); $languages = $plugin->languages; $system = (string) $languages->string( $lang, 'system_prompt' ); /* * What the model may promise about a human (1.22.2). * * The owner's site showed the failure this prevents: the visitor asked to speak to somebody, the answer said * "bạn có thể để lại email", no form existed, and the visitor typed the address into the chat — where it is * stored as a message. The model writes the sentence the visitor reads, so it must be told which of the two * truths is true right now. */ $system .= "\n\n" . MYBOT_Human_Intent::prompt_note( (bool) $plugin->settings->get( 'support_enabled', 0 ) ); // The language instruction sits right after the system prompt so the LLM follows it most closely. $instruction = $languages->instruction( $lang ); if ( '' !== $instruction ) { $system .= "\n\n" . $instruction; } /* * The knowledge lock's note, and it goes here rather than at the end on purpose: it is the * strongest constraint in the whole prompt, so it sits as close to the system prompt as the * language instruction does. This is also the fix for the half of docs/08 muc 6.45 that made * the old quick branch answer from general knowledge — the "answer only from the data below" * note used to be added ONLY when there was a context, which meant the two branches that had * no context were also the two branches with no restriction. */ if ( class_exists( 'MYBOT_Knowledge_Lock' ) && MYBOT_Knowledge_Lock::is_active() ) { $system .= "\n\n" . $languages->lock_note( $lang, $small_talk ? 'smallTalk' : 'strict' ); } if ( '' !== $context ) { $system .= "\n\n" . $languages->rag_note( $lang ); /* * Ask the model to raise a flag it cannot forget, instead of hoping a phrase like * "I don't have that information" shows up so it can be searched for. The marker is * never shown to the visitor: the reply is cleaned before it is stored or returned. * * A marker only works if the model can be told what to do with it, so the instruction * is stated where the context is: at the end, closest to the question. */ if ( mybot()->settings->get( 'support_enabled', 0 ) ) { $system .= "\n\n" . sprintf( /* translators: %s: the marker token the model must append */ __( 'If the information above does not answer the question, say clearly that you do not have that information and append the exact token %s at the very end of your reply, on its own line. Do not use that token in any other case.', 'aihouse' ), self::NO_ANSWER_MARKER ); } $system .= "\n\n---\n" . $context . "\n---"; } $messages = array( array( 'role' => 'system', 'content' => $system, ), ); foreach ( $this->recent_history( $session_id ) as $turn ) { $messages[] = array( 'role' => ( 'bot' === $turn['role'] ) ? 'assistant' : 'user', 'content' => (string) $turn['content'], ); } $messages[] = array( 'role' => 'user', 'content' => $message, ); /* * The picture travels with the visitor's own message (1.14.0). * * It goes through `MYBOT_LLM_Content::parts()` — the one canonical shape from 1.12.0 — so a text * question stays a plain STRING (byte-for-byte what 1.11.1 sent) and only a message that really * carries a picture becomes a list of parts. The base64 is passed as `data`, which is what Gemini * needs and what OpenAI/OpenRouter accept as a data URI, so no provider has to fetch anything and * no public URL for a visitor's photo ever exists. */ if ( ! empty( $attachment ) && isset( $attachment['file'] ) && '' !== (string) $attachment['file'] ) { $path = MYBOT_Attachments::path( (string) $attachment['file'] ); if ( '' !== $path && file_exists( $path ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents $binary = (string) file_get_contents( $path ); $last = count( $messages ) - 1; $parts = MYBOT_LLM_Content::parts( $message ); $parts[] = array( 'type' => MYBOT_LLM_Content::IMAGE, 'data' => base64_encode( $binary ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode 'mime' => (string) $attachment['mime'], 'url' => '', ); $messages[ $last ]['content'] = $parts; } } /** * Filters the message array before it is sent to the LLM. * * @param array $messages Messages. * @param string $session_id Session ID. * @param string $lang Language code. */ $messages = apply_filters( 'mybot_llm_messages', $messages, $session_id, $lang ); /* * Tools an add-on wants the model to be able to call. * * Kept as a SEPARATE seam from `mybot_llm_messages` on purpose, even though both end up in the same * request. A tool is a declared capability with a name, a description and a JSON schema, and the * provider only accepts them in a dedicated field — so an add-on that registers `woo.stock` here does * not have to know how the message array is shaped, and a provider that does not support tools at all * can drop them without touching what the add-on wrote. * * The core does not ship a tool of its own, and that is deliberate: with no add-on installed this * filter returns an empty array and the request is byte-for-byte what it was before the seam existed. * * @param array $tools Tool definitions, keyed by tool name. * @param string $session_id Session ID. * @param string $lang Language code. */ $tools = apply_filters( 'mybot_register_tools', array(), $session_id, $lang ); if ( is_array( $tools ) && ! empty( $tools ) ) { $messages = $this->attach_tools( $messages, $tools ); } return $messages; } /** * Attach registered tools to the outgoing request. * * Tools are attached as a property of the LAST message rather than as a fourth element, because a * conversation is a list of messages and adding a non-message element to it would make every provider * implementation responsible for skipping it. Each tool is normalised to the shape providers expect, and a * malformed one is dropped rather than sent: an invalid schema makes the whole request fail, which would * take down ordinary chat for a feature the visitor may never have asked for. * * @param array $messages Messages. * @param array $tools Tool definitions. * @return array */ protected function attach_tools( $messages, $tools ) { $clean = array(); foreach ( $tools as $name => $tool ) { $name = is_string( $name ) ? trim( $name ) : ''; if ( '' === $name || ! is_array( $tool ) || empty( $tool['parameters'] ) ) { continue; } $clean[] = array( 'type' => 'function', 'function' => array( 'name' => $name, 'description' => isset( $tool['description'] ) ? (string) $tool['description'] : '', 'parameters' => $tool['parameters'], ), ); } if ( ! empty( $clean ) ) { $messages[ count( $messages ) - 1 ]['tools'] = $clean; } return $messages; } /** * Fetches the most recent turns of the session. * * @param string $session_id Session ID. * @return array */ protected function recent_history( $session_id ) { $turns = (int) apply_filters( 'mybot_history_turns', self::HISTORY_TURNS, $session_id ); if ( $turns < 1 ) { return array(); } $rows = mybot()->logger->get_history( $session_id, $turns * 2 ); return array_slice( $rows, -$turns * 2 ); } /** * Fallback reply for when the AI cannot be reached. * * Returns HTTP 200 with a degraded flag so the interface can show a message instead of an error. * * @param string $reason Reason, logged only and never returned to the visitor. * @param string $lang Language of the request, so the one sentence the visitor does read arrives * in the language they wrote in. Until 1.7.0 this sentence came from the * top-level field only, which is the one string that stayed English inside a * Vietnamese conversation (the open item in docs/08 muc 11). * @return array */ protected function degraded_response( $reason, $lang = '' ) { // Store the latest reason so the admin sees it right away on the dashboard, because // the visitor only receives a generic fallback reply. update_option( MYBOT_DEGRADED_OPTION, array( 'at' => time(), 'reason' => (string) $reason, ), false ); mybot()->logger->log( array( 'session_id' => 'system', 'role' => 'bot', 'content' => '[degraded] ' . $reason, 'mode' => 'quick', ) ); $fallback = (string) mybot()->languages->string( $lang, 'fallback_message' ); if ( '' === trim( $fallback ) ) { $fallback = __( 'Sorry, the system is busy.', 'aihouse' ); } return array( 'reply' => $fallback, 'sources' => array(), 'degraded' => true, ); } /** * Receives visitor feedback. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function handle_feedback( $request ) { $session_id = mybot()->security->clean_session_id( (string) $request->get_param( 'session_id' ) ); $rating = (int) $request->get_param( 'rating' ); if ( '' === $session_id ) { return new WP_Error( 'mybot_bad_session', __( 'Missing session ID.', 'aihouse' ), array( 'status' => 400 ) ); } $updated = mybot()->logger->rate_last_bot_message( $session_id, $rating > 0 ? 1 : -1 ); return new WP_REST_Response( array( 'success' => true, 'updated' => (bool) $updated, ), 200 ); } }