230 linhas
10 KiB
PHP
230 linhas
10 KiB
PHP
<?php
|
|
if (!defined('ABSPATH')) {
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* All in One AI assistant: a floating chat on the site.
|
|
* The browser talks only to this WordPress (REST route); WordPress calls POST /v1/chat/completions with the key.
|
|
* The key never goes to the browser. Each visitor has a limit per hour and per day, and the site a limit per day.
|
|
*/
|
|
class MOZOUT_AI_Assistant
|
|
{
|
|
const MAX_HISTORY = 10;
|
|
const MAX_CHARS = 1000;
|
|
|
|
public static function init()
|
|
{
|
|
add_action('rest_api_init', array(__CLASS__, 'routes'));
|
|
add_action('wp_enqueue_scripts', array(__CLASS__, 'assets'));
|
|
}
|
|
|
|
public static function enabled()
|
|
{
|
|
return (int) MOZOUT_AI_Settings::get('ai_enabled') === 1 && MOZOUT_AI_Settings::api_key() !== '' && trim((string) MOZOUT_AI_Settings::get('ai_model')) !== '';
|
|
}
|
|
|
|
private static function text($field, $lang, $default)
|
|
{
|
|
$v = trim((string) MOZOUT_AI_Settings::get($field . '_' . $lang));
|
|
return $v !== '' ? $v : MOZOUT_AI_I18n::in($lang, $default);
|
|
}
|
|
|
|
public static function assets()
|
|
{
|
|
if (!self::enabled() || is_admin()) {
|
|
return;
|
|
}
|
|
if (!apply_filters('mozout_ai_show_assistant', true)) {
|
|
return;
|
|
}
|
|
$lang = MOZOUT_AI_I18n::lang();
|
|
$color = sanitize_hex_color((string) MOZOUT_AI_Settings::get('ai_color'));
|
|
wp_enqueue_style('mozout-ai-chat', MOZOUT_AI_URL . 'assets/chat.css', array(), MOZOUT_AI_VERSION);
|
|
wp_add_inline_style('mozout-ai-chat', '.mozout-ai-chat{--mozout-ai-color:' . ($color ? $color : '#d60037') . ';}');
|
|
wp_enqueue_script('mozout-ai-chat', MOZOUT_AI_URL . 'assets/chat.js', array(), MOZOUT_AI_VERSION, true);
|
|
wp_localize_script('mozout-ai-chat', 'mozoutAiChat', array(
|
|
'url' => esc_url_raw(rest_url('mozout-ai/v1/chat')),
|
|
'lang' => $lang,
|
|
'position' => MOZOUT_AI_Settings::get('ai_position') === 'left' ? 'left' : 'right',
|
|
'title' => self::text('ai_title', $lang, 'Assistant'),
|
|
'welcome' => self::text('ai_welcome', $lang, 'Hello! How can I help you?'),
|
|
'open' => __('Open the assistant', 'mozout-ai'),
|
|
'close' => __('Close the assistant', 'mozout-ai'),
|
|
'placeholder' => __('Write your question...', 'mozout-ai'),
|
|
'send' => __('Send', 'mozout-ai'),
|
|
'thinking' => __('Writing...', 'mozout-ai'),
|
|
'error' => __('The assistant is not available right now. Please try again later.', 'mozout-ai'),
|
|
'note' => __('Answers are written by AI and may have mistakes.', 'mozout-ai'),
|
|
'maxChars' => self::MAX_CHARS,
|
|
));
|
|
}
|
|
|
|
public static function routes()
|
|
{
|
|
register_rest_route('mozout-ai/v1', '/chat', array(
|
|
'methods' => 'POST',
|
|
'callback' => array(__CLASS__, 'rest_chat'),
|
|
'permission_callback' => '__return_true',
|
|
));
|
|
}
|
|
|
|
/** Requests from another site are refused (the browser sends Origin on POST). */
|
|
private static function same_origin(WP_REST_Request $req)
|
|
{
|
|
$origin = $req->get_header('origin');
|
|
if (!$origin) {
|
|
return true;
|
|
}
|
|
$home = wp_parse_url(home_url());
|
|
$o = wp_parse_url($origin);
|
|
return isset($o['host'], $home['host']) && strtolower($o['host']) === strtolower($home['host']);
|
|
}
|
|
|
|
private static function visitor_id(WP_REST_Request $req)
|
|
{
|
|
$vid = isset($_COOKIE['mozout_ai_vid']) ? preg_replace('/[^a-zA-Z0-9]/', '', (string) $_COOKIE['mozout_ai_vid']) : '';
|
|
if (strlen($vid) !== 32) {
|
|
$vid = wp_generate_password(32, false, false);
|
|
if (!headers_sent()) {
|
|
setcookie('mozout_ai_vid', $vid, array(
|
|
'expires' => time() + 30 * DAY_IN_SECONDS,
|
|
'path' => COOKIEPATH ? COOKIEPATH : '/',
|
|
'secure' => is_ssl(),
|
|
'httponly' => true,
|
|
'samesite' => 'Lax',
|
|
));
|
|
}
|
|
}
|
|
return $vid;
|
|
}
|
|
|
|
private static function out($ok, $payload, $status = 200)
|
|
{
|
|
return new WP_REST_Response(array_merge(array('ok' => $ok), $payload), $status);
|
|
}
|
|
|
|
public static function rest_chat(WP_REST_Request $req)
|
|
{
|
|
$lang = $req->get_param('lang') === 'pt' ? 'pt' : 'en';
|
|
$t = function ($s) use ($lang) {
|
|
return MOZOUT_AI_I18n::in($lang, $s);
|
|
};
|
|
if (!self::enabled()) {
|
|
return self::out(false, array('message' => $t('The assistant is not available right now. Please try again later.')), 503);
|
|
}
|
|
if (!self::same_origin($req)) {
|
|
return self::out(false, array('message' => 'forbidden'), 403);
|
|
}
|
|
|
|
// Conversation sent by the browser: only user and assistant turns, short, and the last 10.
|
|
$in = $req->get_param('messages');
|
|
$messages = array();
|
|
if (is_array($in)) {
|
|
foreach (array_slice($in, -self::MAX_HISTORY) as $m) {
|
|
if (!is_array($m) || !isset($m['role'], $m['content'])) {
|
|
continue;
|
|
}
|
|
$role = $m['role'] === 'assistant' ? 'assistant' : 'user';
|
|
$content = trim(wp_strip_all_tags((string) $m['content']));
|
|
if ($content === '') {
|
|
continue;
|
|
}
|
|
$content = function_exists('mb_substr') ? mb_substr($content, 0, self::MAX_CHARS) : substr($content, 0, self::MAX_CHARS);
|
|
$messages[] = array('role' => $role, 'content' => $content);
|
|
}
|
|
}
|
|
if (!$messages || end($messages)['role'] !== 'user') {
|
|
return self::out(false, array('message' => $t('Write your question first.')), 422);
|
|
}
|
|
|
|
// Limits: per visitor (cookie and IP, whichever is reached first) and for the whole site.
|
|
$ip = self::client_ip();
|
|
$vid = self::visitor_id($req);
|
|
$hour = max(1, (int) MOZOUT_AI_Settings::get('ai_per_hour'));
|
|
$day = max(1, (int) MOZOUT_AI_Settings::get('ai_per_day'));
|
|
$site_day = (int) MOZOUT_AI_Settings::get('ai_site_per_day');
|
|
$today = gmdate('Ymd');
|
|
$buckets = array(
|
|
array('ai_h_ip_' . $ip . gmdate('YmdH'), $hour, HOUR_IN_SECONDS),
|
|
array('ai_h_v_' . $vid . gmdate('YmdH'), $hour, HOUR_IN_SECONDS),
|
|
array('ai_d_ip_' . $ip . $today, $day, DAY_IN_SECONDS),
|
|
array('ai_d_v_' . $vid . $today, $day, DAY_IN_SECONDS),
|
|
);
|
|
foreach ($buckets as $b) {
|
|
if ((int) get_transient('mozout_ai_rl_' . md5($b[0])) >= $b[1]) {
|
|
return self::out(false, array('message' => $t('You reached the message limit for now. Please try again later.')), 429);
|
|
}
|
|
}
|
|
if ($site_day > 0 && (int) get_transient('mozout_ai_rl_' . md5('ai_site_' . $today)) >= $site_day) {
|
|
return self::out(false, array('message' => $t('The assistant reached its limit for today. Please try again tomorrow.')), 429);
|
|
}
|
|
foreach ($buckets as $b) {
|
|
self::rate_ok($b[0], $b[1], $b[2]);
|
|
}
|
|
if ($site_day > 0) {
|
|
self::rate_ok('ai_site_' . $today, $site_day, DAY_IN_SECONDS);
|
|
}
|
|
|
|
$model = trim((string) MOZOUT_AI_Settings::get('ai_model'));
|
|
$body = array(
|
|
'model' => $model,
|
|
'messages' => $messages,
|
|
'max_tokens' => min(2000, max(50, (int) MOZOUT_AI_Settings::get('ai_max_tokens'))),
|
|
);
|
|
// An agent already has its instructions; a plain model gets the ones from the settings.
|
|
if (strpos($model, 'agent/') !== 0) {
|
|
array_unshift($body['messages'], array('role' => 'system', 'content' => self::instructions($lang)));
|
|
}
|
|
|
|
$res = MOZOUT_AI_Api::request('POST', '/v1/chat/completions', $body, array('timeout' => 45, 'lang' => $lang));
|
|
if (is_wp_error($res)) {
|
|
MOZOUT_AI_Log::add('ai', false, $res->get_error_message());
|
|
return self::out(false, array('message' => $t('The assistant is not available right now. Please try again later.')), 502);
|
|
}
|
|
$data = $res['raw'];
|
|
$answer = isset($data['choices'][0]['message']['content']) ? trim((string) $data['choices'][0]['message']['content']) : '';
|
|
if ($answer === '') {
|
|
MOZOUT_AI_Log::add('ai', false, __('The model answered without text.', 'mozout-ai'));
|
|
return self::out(false, array('message' => $t('The assistant is not available right now. Please try again later.')), 502);
|
|
}
|
|
return self::out(true, array('answer' => $answer));
|
|
}
|
|
|
|
public static function client_ip()
|
|
{
|
|
$ip = isset($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : '';
|
|
$ip = apply_filters('mozout_ai_client_ip', $ip);
|
|
return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '0.0.0.0';
|
|
}
|
|
|
|
/** Counts actions per key in a time window; false when the limit has been reached. */
|
|
public static function rate_ok($bucket, $limit, $window)
|
|
{
|
|
if ($limit <= 0) {
|
|
return true;
|
|
}
|
|
$key = 'mozout_ai_rl_' . md5($bucket);
|
|
$n = (int) get_transient($key);
|
|
if ($n >= $limit) {
|
|
return false;
|
|
}
|
|
set_transient($key, $n + 1, $window);
|
|
return true;
|
|
}
|
|
|
|
public static function instructions($lang)
|
|
{
|
|
$custom = trim((string) MOZOUT_AI_Settings::get('ai_instructions'));
|
|
$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
|
|
$base = $custom !== '' ? $custom : sprintf(
|
|
'You are the assistant of the website "%1$s" (%2$s). Answer questions about the website, its products and services, briefly and politely. If you do not know something, say so and suggest contacting the team. Do not invent prices, deadlines or promises.',
|
|
$site,
|
|
home_url('/')
|
|
);
|
|
$base .= "\n\n" . ($lang === 'pt'
|
|
? 'Responde em português europeu, salvo se o visitante escrever noutra língua.'
|
|
: 'Answer in English, unless the visitor writes in another language.');
|
|
return $base;
|
|
}
|
|
}
|