Connectors: the plugin never asks for, reads or stores an API key */ use WordPress\AiClient\AiClient; use WordPress\AiClient\Messages\DTO\Message; use WordPress\AiClient\Messages\DTO\MessagePart; use WordPress\AiClient\Messages\DTO\ModelMessage; use WordPress\AiClient\Messages\DTO\UserMessage; use WordPress\AiClient\Providers\Http\DTO\RequestOptions; use WordPress\AiClient\Providers\Models\DTO\ModelConfig; use WordPress\AiClient\Tools\DTO\FunctionDeclaration; use WordPress\AiClient\Tools\DTO\FunctionResponse; // Model of each service: a fixed version, changed only after being tested, so every site gets the answers and the // prices it was tested with (can be changed in wp-config.php). gemini-3.8-flash was tested and ignored the site // owner's instructions if( ! defined( 'VELISCHAT_OPENAI_MODEL' ) ){ define( 'VELISCHAT_OPENAI_MODEL', 'gpt-6-luna' ); } if( ! defined( 'VELISCHAT_GEMINI_MODEL' ) ){ define( 'VELISCHAT_GEMINI_MODEL', 'gemini-3-flash-preview' ); } if( ! defined( 'VELISCHAT_CLAUDE_MODEL' ) ){ define( 'VELISCHAT_CLAUDE_MODEL', 'claude-haiku-5-5' ); } // How much ChatGPT and Claude think before answering: more is slower and costs more (can be changed in wp-config.php) if( ! defined( 'VELISCHAT_OPENAI_EFFORT' ) ){ define( 'VELISCHAT_OPENAI_EFFORT', 'low' ); } if( ! defined( 'VELISCHAT_CLAUDE_EFFORT' ) ){ define( 'VELISCHAT_CLAUDE_EFFORT', 'low' ); } // Seconds all the calls to the AI for one message can take: many web servers cut a request after 30 seconds, // and the visitor would only get a generic error with nothing in the log (can be raised in wp-config.php) if( ! defined( 'VELISCHAT_AI_TIME_LIMIT' ) ){ define( 'VELISCHAT_AI_TIME_LIMIT', 25 ); } // Calls to the AI for one message: a big shop needs a few of them just to search, and the time limit still applies define( 'VELISCHAT_AI_MAX_ROUNDS', 6 ); // Longest part of a conversation sent to the AI, about 20,000 tokens (can be changed in wp-config.php) if( ! defined( 'VELISCHAT_AI_MAX_HISTORY_CHARS' ) ){ define( 'VELISCHAT_AI_MAX_HISTORY_CHARS', 45000 ); } // Longest answer to a visitor, thinking included define( 'VELISCHAT_AI_MAX_TOKENS', 16000 ); function velischat_get_ai_providers(){ // AI services the chatbot can use. 'connector' is the service in Settings > Connectors, 'model' and 'options' what // every request asks of it (the options are the service's own request fields). 'pricing' feeds the price estimate // in the settings: list prices in dollars per million tokens of the model (October 2026), and conversations per // million tokens measured with 5-message conversations on a sample restaurant site with about 40 products. // 'billing_url' is the page where the site owner tops up the prepaid credit. The default service comes first return array( 'openai' => array( 'name' => 'ChatGPT', 'company' => 'OpenAI', 'description' => __( 'OpenAI\'s GPT-6 Luna model.', 'velischat' ), 'connector' => 'openai', 'model' => VELISCHAT_OPENAI_MODEL, // Nothing is kept by OpenAI: the conversation lives in the PHP session, and the reasoning of a message goes // back encrypted with its function calls 'options' => array( 'reasoning' => array( 'effort' => VELISCHAT_OPENAI_EFFORT ), 'store' => false, 'include' => array( 'reasoning.encrypted_content' ) ), 'key_url' => 'https://platform.openai.com/api-keys', 'pricing_url' => 'https://developers.openai.com/api/docs/pricing', 'billing_url' => 'https://platform.openai.com/settings/organization/billing/overview', 'pricing' => array( 'model' => 'GPT-6 Luna', 'input' => 0.10, 'cached' => 0.01, 'output' => 0.50, 'conversations' => 20, 'cost_per_1000' => 1.2 ), ), 'gemini' => array( 'name' => 'Gemini', 'company' => 'Google', 'description' => __( 'Google\'s Gemini Flash model.', 'velischat' ), 'connector' => 'google', 'model' => VELISCHAT_GEMINI_MODEL, // Little thinking: with the default level a message with a proposal can take more than 25 seconds 'options' => array( 'generationConfig.thinkingConfig' => array( 'thinkingLevel' => 'low' ) ), 'temperature' => 0.0, 'key_url' => 'https://aistudio.google.com/apikey', 'pricing_url' => 'https://ai.google.dev/gemini-api/docs/pricing', 'billing_url' => 'https://aistudio.google.com/billing', 'pricing' => array( 'model' => 'Gemini 3 Flash', 'input' => 0.50, 'cached' => 0.05, 'output' => 3.00, 'conversations' => 15, 'cost_per_1000' => 24 ), ), 'claude' => array( 'name' => 'Claude', 'company' => 'Anthropic', 'description' => __( 'Anthropic\'s Claude Haiku model.', 'velischat' ), 'connector' => 'anthropic', 'model' => VELISCHAT_CLAUDE_MODEL, // The whole request is cached: the rounds after a function call, and the next messages, reread it at a // tenth of the price. The system instructions get their own mark (see velischat_ai_prompt()) 'options' => array( 'output_config' => array( 'effort' => VELISCHAT_CLAUDE_EFFORT ), 'cache_control' => array( 'type' => 'ephemeral' ) ), 'system_cache' => true, // The site contents after the instructions, as up to version 0.9: before them, Claude often wrote its // reasoning about the language in the answer ("The user writes in Italian, so I answer in Italian") 'contents_last' => true, 'key_url' => 'https://platform.claude.com/settings/keys', 'pricing_url' => 'https://platform.claude.com/docs/en/about-claude/pricing', 'billing_url' => 'https://platform.claude.com/settings/billing', 'pricing' => array( 'model' => 'Claude Haiku 5.5', 'input' => 0.10, 'cached' => 0.01, 'output' => 0.50, 'conversations' => 12, 'cost_per_1000' => 3.2 ), ), ); } function velischat_get_ai_provider_logo( $provider ){ // URL of the service's logo, shown next to its name in the settings: the official file, added to // assets/images/ai/ as .svg or .png. Without the file only the name is shown foreach( array( 'svg', 'png' ) as $extension ){ $file = 'assets/images/ai/' . $provider . '.' . $extension; if( file_exists( VELISCHAT_PATH . $file ) ){ return VELISCHAT_URL . $file; } } return ''; } function velischat_sanitize_ai_provider( $provider ){ // Only the services above are accepted, otherwise the default one return array_key_exists( $provider, velischat_get_ai_providers() ) ? $provider : 'openai'; } function velischat_get_ai_provider(){ // AI service chosen in the settings return velischat_sanitize_ai_provider( get_option( 'velischat_ai_provider', '' ) ); } function velischat_get_ai_provider_name( $provider = null ){ // Name of the given AI service (by default the chosen one), e.g. "Gemini" return velischat_get_ai_providers()[ $provider ?? velischat_get_ai_provider() ][ 'name' ]; } function velischat_get_connectors_url(){ // Settings > Connectors, where the site owner installs the service's connector and enters its API key return admin_url( 'options-connectors.php' ); } function velischat_get_ai_status( $provider = null ){ // Whether the given AI service (by default the chosen one) can answer: // 'unsupported': this WordPress has no AI Client; // 'disabled': AI features are turned off on this site; // 'plugin': the service's connector isn't installed and active in Settings > Connectors; // 'key': the connector is there, without an API key; // 'ready': connected if( ! function_exists( 'wp_ai_client_prompt' ) || ! class_exists( AiClient::class ) ){ return 'unsupported'; } if( ! wp_supports_ai() ){ return 'disabled'; } $connector = velischat_get_ai_providers()[ $provider ?? velischat_get_ai_provider() ][ 'connector' ]; try { $registry = AiClient::defaultRegistry(); if( ! $registry->hasProvider( $connector ) ){ return 'plugin'; } return null === $registry->getProviderRequestAuthentication( $connector ) ? 'key' : 'ready'; } catch( Exception $e ){ return 'plugin'; } } function velischat_ai_is_ready(){ // The chosen AI service is connected: the chatbot can answer return velischat_get_ai_status() === 'ready'; } function velischat_get_ai_status_text( $status, $provider = null ){ // What the site owner has to do for the given status, in one sentence $name = velischat_get_ai_provider_name( $provider ); $company = velischat_get_ai_providers()[ $provider ?? velischat_get_ai_provider() ][ 'company' ]; switch( $status ){ case 'unsupported': return __( 'VelisChat needs WordPress 7.0 or later, which connects the AI services: update WordPress.', 'velischat' ); case 'disabled': return __( 'AI features are turned off on this site: the chatbot can\'t answer until they are turned on again.', 'velischat' ); case 'plugin': /* translators: 1: name of the AI service, e.g. "ChatGPT", 2: company, e.g. "OpenAI" */ return sprintf( __( 'To use %1$s, install and activate the %2$s connector in Settings → Connectors.', 'velischat' ), $name, $company ); case 'key': /* translators: 1: name of the AI service, e.g. "ChatGPT", 2: company, e.g. "OpenAI" */ return sprintf( __( 'To use %1$s, enter your %2$s API key in Settings → Connectors.', 'velischat' ), $name, $company ); default: /* translators: %s: company, e.g. "OpenAI" */ return sprintf( __( 'The chatbot uses your %s account, set up in Settings → Connectors.', 'velischat' ), $company ); } } function velischat_get_api_key(){ // Up to version 0.9 the plugin kept the API key itself, and code written for those versions checks whether one is // set: it is now "set" when the chosen service is connected. Deprecated: use velischat_ai_is_ready() return velischat_ai_is_ready() ? 'connectors' : ''; } /** * * * Requests */ function velischat_ai_model( $config ){ // The service's model chosen by the plugin. Null when the service doesn't list it (e.g. a model retired): the // AI Client then picks the closest one of the service, and the log says so try { return AiClient::defaultRegistry()->getProviderModel( $config[ 'connector' ], $config[ 'model' ] ); } catch( Exception $e ){ velischat_log( 'model ' . $config[ 'model' ] . ' not available: ' . $e->getMessage() ); return null; } } function velischat_ai_prompt( $prompt, $system, $max_tokens, $timeout, $tools = array() ){ // A request to the chosen AI service, ready to be sent: its model and options, the system instructions, the longest // answer, the seconds it can take and the functions the AI can call. $prompt is the text or the messages to send $config = velischat_get_ai_providers()[ velischat_get_ai_provider() ]; $builder = wp_ai_client_prompt( $prompt ); $model = velischat_ai_model( $config ); if( $model ){ $builder->using_model( $model ); } else { $builder->using_provider( $config[ 'connector' ] )->using_model_preference( $config[ 'model' ] ); } $options = $config[ 'options' ]; if( $system !== '' ){ if( ! empty( $config[ 'system_cache' ] ) ){ // Claude: the instructions and the contents are the same for every visitor, and with their own cache mark // they're read at a tenth of the price from the second message on, by every visitor $options[ 'system' ] = array( array( 'type' => 'text', 'text' => $system, 'cache_control' => array( 'type' => 'ephemeral' ) ) ); } else { $builder->using_system_instruction( $system ); } } $model_config = new ModelConfig(); $model_config->setCustomOptions( $options ); $builder->using_model_config( $model_config ); if( isset( $config[ 'temperature' ] ) ){ $builder->using_temperature( (float) $config[ 'temperature' ] ); } $builder->using_max_tokens( (int) $max_tokens ); $builder->using_request_options( RequestOptions::fromArray( array( RequestOptions::KEY_TIMEOUT => max( 1.0, (float) $timeout ) ) ) ); if( $tools ){ $builder->using_function_declarations( ...$tools ); } return $builder; } function velischat_ai_send( $builder ){ // Send a request: the result, or WP_Error. Every answer tells whether the AI credit is out $result = $builder->generate_text_result(); velischat_note_ai_credit( $result ); return $result; } function velischat_ai_function_declarations(){ // The functions added by the add-ons (velischat_get_ai_tools(), in the format of Gemini's "tools" field) for the // AI Client: same names, descriptions and parameters $declarations = array(); foreach( velischat_get_ai_tools() as $group ){ foreach( $group[ 'functionDeclarations' ] ?? array() as $function ){ if( empty( $function[ 'name' ] ) ){ continue; } $declarations[] = new FunctionDeclaration( (string) $function[ 'name' ], (string) ( $function[ 'description' ] ?? '' ), isset( $function[ 'parameters' ] ) && is_array( $function[ 'parameters' ] ) ? $function[ 'parameters' ] : null ); } } return $declarations; } function velischat_ai_error_timed_out( $error ){ // The request ran out of time: cURL reports "cURL error 28: Operation timed out", the other transports "timed out" $message = $error->get_error_message(); return $error->get_error_code() === 'prompt_network_error' && ( strpos( $message, 'cURL error 28' ) !== false || stripos( $message, 'timed out' ) !== false ); } function velischat_ai_error_message( $error ){ // Readable cause of a failed request, for the PHP error log and the administrators: the service's answer, never // the API key return velischat_get_ai_provider_name() . ': ' . $error->get_error_message(); } function velischat_ai_result_messages( $result ){ // The messages of an answer. ChatGPT sends each function call as an answer of its own: all of them count $messages = array(); foreach( $result->getCandidates() as $candidate ){ $messages[] = $candidate->getMessage(); } return $messages; } function velischat_ai_result_refused( $result ){ // The service's safety checks declined the request: the answer has no reply foreach( $result->getCandidates() as $candidate ){ if( $candidate->getFinishReason()->isContentFilter() ){ return true; } } return false; } function velischat_ai_messages_text( $messages ){ // Text of an answer: its text parts, without the thinking and the function calls $text = ''; foreach( $messages as $message ){ foreach( $message->getParts() as $part ){ if( $part->getChannel()->isContent() && $part->getType()->isText() ){ $text .= (string) $part->getText(); } } } return trim( $text ); } function velischat_ai_messages_calls( $messages ){ // The functions the AI asked to call in an answer $calls = array(); foreach( $messages as $message ){ foreach( $message->getParts() as $part ){ if( $part->getType()->isFunctionCall() && $part->getFunctionCall() ){ $calls[] = $part->getFunctionCall(); } } } return $calls; } function velischat_ai_add_text( $messages, $text ){ // A text for the AI after the last message, only in this call. ChatGPT takes it as a message of its own (the result // of a function must be alone in its message), the others next to the last one, as the earlier versions did $last = end( $messages ); if( velischat_get_ai_provider() !== 'openai' && $last instanceof Message && $last->getRole()->isUser() ){ $messages[ count( $messages ) - 1 ] = new UserMessage( array_merge( $last->getParts(), array( new MessagePart( $text ) ) ) ); return $messages; } $messages[] = new UserMessage( array( new MessagePart( $text ) ) ); return $messages; } /** * * * The conversation */ function velischat_ai_history_key(){ // Session key of the conversation with the chosen AI service, in the format of the AI Client: each service has // its own, since what one service writes (signatures, encrypted reasoning) can only go back to that service return 'velischat_ai_history_' . velischat_get_ai_provider(); } function velischat_ai_save_messages( $messages ){ // Add messages to the conversation kept in the session. Claude's thinking is left out: it is only valid in the // request it was made for, and the instructions it depends on can change before the next message $turns = array(); foreach( $messages as $message ){ $parts = $message->getParts(); if( velischat_get_ai_provider() === 'claude' ){ $parts = array_values( array_filter( $parts, function( $part ){ return ! $part->getChannel()->isThought(); } ) ); } if( $parts ){ $turns[] = ( new Message( $message->getRole(), $parts ) )->toArray(); } } velischat_add_to_history( velischat_ai_history_key(), $turns ); } function velischat_ai_save_reply( $reply, $messages = array() ){ // Add the reply to the conversation: the AI's answer as received when the reply is its text, otherwise (a line // written by the plugin, names masked) the reply as text. The text alone also goes to the conversation read by the // email summary if( ! $messages || velischat_ai_messages_text( $messages ) !== $reply ){ $messages = array( new ModelMessage( array( new MessagePart( $reply ) ) ) ); } velischat_ai_save_messages( $messages ); velischat_add_to_history( 'velischat_chat_history', array( array( 'role' => 'model', 'parts' => array( array( 'text' => $reply ) ) ) ) ); } function velischat_ai_out_of_time( $timings ){ // The AI took too long: the cards already prepared are shown with a short line, otherwise it's an error $log = velischat_get_ai_provider_name() . ' did not answer within ' . VELISCHAT_AI_TIME_LIMIT . ' seconds (rounds took ' . implode( 's, ', $timings ) . 's).'; $reply = velischat_ai_fallback_reply(); if( $reply === '' ){ return new WP_Error( 'ai_timeout', $log ); } velischat_log( $log ); velischat_ai_save_reply( $reply ); return $reply; } function velischat_ai_session_messages(){ // The part of the conversation sent to the AI, as messages of the AI Client. With an item that can't be read // anymore it's empty, and the AI gets only the visitor's latest message $messages = array(); foreach( velischat_history_window( velischat_ai_history_key() ) as $turn ){ try { $messages[] = Message::fromArray( $turn ); } catch( Exception $e ){ velischat_log( 'unreadable message in the conversation: ' . $e->getMessage() ); return array(); } } return $messages; } function velischat_ai_system_text(){ // System instructions of every answer: the site contents, then the instructions, so the rule on the language // stays the last thing the AI reads. As a message of their own before the conversation, the contents made Gemini // answer some English and German questions in the language of the site; here every answer was in the visitor's // language. Claude takes them in the other order (see velischat_get_ai_providers()). The same text at every // message, so the services cache it $instructions = velischat_get_ai_instructions(); $context = velischat_get_context_text(); if( $context === '' ){ return trim( $instructions ); } $document = "Document with the site's content:\n\n" . $context . "\n"; if( ! empty( velischat_get_ai_providers()[ velischat_get_ai_provider() ][ 'contents_last' ] ) ){ return trim( $instructions . "\n\n" . $document ); } return trim( $document . "\n\n" . $instructions ); } function velischat_ai_call( $message ){ // Answer the visitor's message with the AI service chosen in the settings velischat_session_start(); if( ! velischat_ai_is_ready() ){ return new WP_Error( 'ai_not_ready', velischat_get_ai_status_text( velischat_get_ai_status() ) ); } // The visitor can't point the AI at its own functions by name $text = velischat_mask_internal_names( $message ); velischat_ai_save_messages( array( new UserMessage( array( new MessagePart( $text ) ) ) ) ); velischat_add_to_history( 'velischat_chat_history', array( array( 'role' => 'user', 'parts' => array( array( 'text' => $text ) ) ) ) ); $messages = velischat_ai_session_messages(); if( ! $messages ){ $messages = array( new UserMessage( array( new MessagePart( $text ) ) ) ); } // The language of the answer, next to the visitor's message (only in this call, not in the saved conversation) $last = end( $messages ); $messages[ count( $messages ) - 1 ] = new UserMessage( array_merge( $last->getParts(), array( new MessagePart( velischat_get_language_reminder() ) ) ) ); $system = velischat_ai_system_text(); $tools = velischat_ai_function_declarations(); // When the AI calls a function, its result goes back to the AI until it writes the reply. A few rounds at most: // a proposal outside the budget is usually fixed at the second try $retried = false; $text_call_run = false; $started = microtime( true ); $timings = array(); for( $round = 0; $round < VELISCHAT_AI_MAX_ROUNDS; $round++ ){ // Each round only gets the time left, and isn't started when there's too little to get an answer $time_left = VELISCHAT_AI_TIME_LIMIT - ( microtime( true ) - $started ); if( $time_left < 3 ){ return velischat_ai_out_of_time( $timings ); } $round_started = microtime( true ); $result = velischat_ai_send( velischat_ai_prompt( $messages, $system, VELISCHAT_AI_MAX_TOKENS, floor( $time_left ), $tools ) ); $timings[] = round( microtime( true ) - $round_started, 1 ); if( is_wp_error( $result ) ){ if( velischat_ai_error_timed_out( $result ) ){ return velischat_ai_out_of_time( $timings ); } return new WP_Error( 'ai_error', velischat_ai_error_message( $result ) ); } if( $round === 0 && $result->getModelMetadata()->getId() !== velischat_get_ai_providers()[ velischat_get_ai_provider() ][ 'model' ] ){ velischat_log( 'answered by the model ' . $result->getModelMetadata()->getId() . ' instead of the chosen one.' ); } // The service's safety checks can decline a request: the answer has no reply if( velischat_ai_result_refused( $result ) ){ return new WP_Error( 'ai_refusal', velischat_get_ai_provider_name() . ' refused to answer.' ); } $answer = velischat_ai_result_messages( $result ); $calls = velischat_ai_messages_calls( $answer ); if( empty( $calls ) ){ $reply = velischat_ai_messages_text( $answer ); // A function call written as text is run as if the AI had called it, and its result goes back to the AI // as text (only in this call: the saved conversation must not teach it to write calls this way). // Once only: if it does it again, the cards already prepared are shown with a short line $text_call = velischat_find_text_function_call( $reply ); if( $text_call ){ if( ! $text_call_run ){ $text_call_run = true; $function = velischat_run_ai_function( $text_call[ 'name' ], $text_call[ 'args' ] ); $messages = array_merge( $messages, $answer ); $messages[] = new UserMessage( array( new MessagePart( 'Result of the function ' . $text_call[ 'name' ] . ': ' . wp_json_encode( $function ) . "\n\nNever write function calls in the text. Now write the message for the user, following what the result of the function told you." ) ) ); continue; } $reply = velischat_ai_fallback_reply(); if( $reply === '' ){ return new WP_Error( 'ai_text_call', velischat_get_ai_provider_name() . ' wrote a function call as text instead of answering: ' . $text_call[ 'name' ] ); } } $reply = velischat_mask_internal_names( $reply ); // After a function call the AI sometimes ends without text, and asking again the same way gets the same // empty answer: ask once more with an explicit request (only in this call), then fall back to a short // line so the cards it asked for are still shown if( $reply === '' && $round > 0 ){ if( ! $retried ){ $retried = true; $messages = velischat_ai_add_text( $messages, 'Now write the message for the user, following what the result of the function told you.' ); continue; } $reply = velischat_ai_fallback_reply(); } if( $reply === '' ){ return new WP_Error( 'ai_empty', velischat_get_ai_provider_name() . ' answered without text.' ); } // Answers close to the limit are logged, to see which rounds are slow before the limit is reached if( microtime( true ) - $started > VELISCHAT_AI_TIME_LIMIT * 0.6 ){ velischat_log( 'slow answer from ' . velischat_get_ai_provider_name() . ' (rounds took ' . implode( 's, ', $timings ) . 's).' ); } velischat_ai_save_reply( $reply, $answer ); return $reply; } // The answer goes back exactly as received (Gemini needs its signatures, ChatGPT its reasoning), followed by // the results of the calls: one message for all of them, or one each for ChatGPT, which takes a result // only alone in its message $results = array(); foreach( $calls as $call ){ $args = $call->getArgs(); $results[] = new MessagePart( new FunctionResponse( $call->getId(), $call->getName(), velischat_run_ai_function( (string) $call->getName(), is_array( $args ) ? $args : array() ) ) ); } if( velischat_get_ai_provider() === 'openai' ){ $replies = array_map( function( $part ){ return new UserMessage( array( $part ) ); }, $results ); } else { $replies = array( new UserMessage( $results ) ); } $messages = array_merge( $messages, $answer, $replies ); velischat_ai_save_messages( array_merge( $answer, $replies ) ); } return new WP_Error( 'ai_loop', velischat_get_ai_provider_name() . ' called the functions too many times without answering.' ); } function velischat_ai_generate_text( $instructions, $text, $max_tokens = 4000, $timeout = 30 ){ // One request, one text answer, with the AI service chosen in the settings: the conversation summary in the // contact email, and what the add-ons ask $status = velischat_get_ai_status(); if( $status !== 'ready' ){ return new WP_Error( 'ai_not_ready', velischat_summary_error_text( velischat_get_ai_status_text( $status ) ) ); } $builder = velischat_ai_prompt( null, (string) $instructions, $max_tokens, $timeout ); // Add-ons can add to the request, e.g. a file for the AI to read: before the text, so their parts come first $filtered = apply_filters( 'velischat_ai_generate_text_prompt', $builder, velischat_get_ai_provider() ); if( $filtered instanceof WP_AI_Client_Prompt_Builder ){ $builder = $filtered; } $builder->with_text( (string) $text ); $result = velischat_ai_send( $builder ); if( is_wp_error( $result ) ){ // A text cut by the limit is not a usable answer if( $result->get_error_code() === 'prompt_token_limit_reached' ){ return new WP_Error( 'ai_text_incomplete', velischat_summary_error_text( velischat_summary_cut_text( 'max_tokens' ) ) ); } return new WP_Error( 'ai_text_error', velischat_summary_error_text( velischat_ai_error_message( $result ) ) ); } // Nor is a refused one, or one stopped before the end $candidate = $result->getCandidates()[ 0 ] ?? null; if( ! $candidate || $candidate->getFinishReason()->isContentFilter() ){ return new WP_Error( 'ai_text_refusal', velischat_summary_error_text( velischat_get_ai_provider_name() . ' refused to answer.' ) ); } if( $candidate->getFinishReason()->isLength() ){ return new WP_Error( 'ai_text_incomplete', velischat_summary_error_text( velischat_summary_cut_text( 'length' ) ) ); } return velischat_ai_messages_text( velischat_ai_result_messages( $result ) ); } /** * * * AI credit: the site owner pays the AI service with prepaid credit. When it runs out the service refuses every request: * the plugin notices it, warns the owner (admin notice + one email) and offers visitors the contact form meanwhile */ // While the credit is out, the AI is asked again at most this often (in seconds): no visitor waits for a sure refusal, // and once the owner tops up the chatbot starts again by itself if( ! defined( 'VELISCHAT_CREDIT_RETRY' ) ){ define( 'VELISCHAT_CREDIT_RETRY', 5 * MINUTE_IN_SECONDS ); } function velischat_is_ai_credit_error( $error ){ // Whether the AI service refused a request because the account's credit is used up or a spending limit was reached. // The AI Client gives the HTTP status and the service's message. OpenAI: 429 "You exceeded your current quota, // please check your plan and billing details"; Claude: "Your credit balance is too low"; Gemini: 402, or 429 // "prepayment credits are depleted" $data = $error->get_error_data(); $status = is_array( $data ) && isset( $data[ 'status' ] ) ? (int) $data[ 'status' ] : 0; if( $error->get_error_code() !== 'prompt_client_error' ){ return false; } if( $status === 402 ){ return true; } if( ! in_array( $status, array( 400, 403, 429 ), true ) ){ return false; } return (bool) preg_match( '/insufficient_quota|credit_balance|billing_error|credit balance|prepayment credits|credits are depleted|plan and billing/i', $error->get_error_message() ); } function velischat_get_ai_credit_out(){ // The credit of the chosen AI service is out: [ 'provider', 'since', 'checked' ], or null. A flag left by another // service doesn't count, since its credit is no longer used $out = get_option( 'velischat_ai_credit_out' ); return is_array( $out ) && ( $out[ 'provider' ] ?? '' ) === velischat_get_ai_provider() ? $out : null; } function velischat_note_ai_credit( $result ){ // After every AI request: an answer clears the "credit out" flag, a refusal for credit sets it (and the owner gets // one email per outage) $out = get_option( 'velischat_ai_credit_out' ); if( ! is_wp_error( $result ) ){ if( $out ){ delete_option( 'velischat_ai_credit_out' ); } return; } if( ! velischat_is_ai_credit_error( $result ) ){ return; } $provider = velischat_get_ai_provider(); $known = is_array( $out ) && ( $out[ 'provider' ] ?? '' ) === $provider; update_option( 'velischat_ai_credit_out', array( 'provider' => $provider, 'since' => $known ? $out[ 'since' ] : time(), 'checked' => time(), ) ); if( ! $known ){ // At the end of the request: the email is in the site's main language, the visitor's answer isn't add_action( 'shutdown', 'velischat_send_ai_credit_email' ); } } function velischat_ai_credit_skip_call(){ // Visitors don't wait for a refusal that is certain: while the credit is out, the AI is asked again only every // few minutes. Administrators always try, so they see the real answer of the service $out = velischat_get_ai_credit_out(); return $out && ! current_user_can( 'manage_options' ) && time() - (int) $out[ 'checked' ] < VELISCHAT_CREDIT_RETRY; }