Skip to content
wiki.fftac.org

AI Engine - Source Excerpt 06

Back to AI Engine

Summary

This source excerpt preserves a bounded section of Anti-Christ.org/wp-content/plugins/fftac-ai-engine/inc/ai-engine.php so readers can inspect the evidence without opening the full source file.

**Source path:** Anti-Christ.org/wp-content/plugins/fftac-ai-engine/inc/ai-engine.php

* Formats a local transcript into a single input message.
 *
 * @param string                             $prompt Current prompt.
 * @param array<int, array<string, string>> $history Conversation history.
 * @return string
 */
function antichrist_engine_foundation_ai_format_transcript($prompt, $history = array())
{
    $sections = array();

    if ($history) {
        $lines = array('Conversation so far, oldest to newest:');

        foreach ($history as $message) {
            $label = 'assistant' === ($message['role'] ?? '') ? 'Assistant' : 'User';
            $lines[] = $label . ': ' . trim((string) ($message['content'] ?? ''));
        }

        $sections[] = implode("\n", $lines);
    }

    $sections[] = 'Current user prompt:' . "\n" . trim((string) $prompt);

    return implode("\n\n", $sections);
}

/**
 * Builds the Responses API payload.
 *
 * @param string                             $prompt Current prompt.
 * @param array<int, array<string, string>> $history Conversation history.
 * @param string                             $persona_key Persona key.
 * @param string                             $key_source Key source.
 * @param string                             $protocol_key Inquiry protocol key.
 * @return array<string, mixed>
 */
function antichrist_engine_foundation_ai_build_response_payload($prompt, $history = array(), $persona_key = '', $key_source = 'site', $protocol_key = '')
{
    $key_source = 'user' === $key_source ? 'user' : 'site';

    return array(
        'model'             => antichrist_engine_foundation_ai_get_model(),
        'instructions'      => antichrist_engine_foundation_ai_get_instructions($persona_key, $protocol_key),
        'input'             => array(
            array(
                'role'    => 'user',
                'content' => array(
                    array(
                        'type' => 'input_text',
                        'text' => antichrist_engine_foundation_ai_format_transcript($prompt, $history),
                    ),
                ),
            ),
        ),
        'max_output_tokens' => antichrist_engine_foundation_ai_get_max_output_tokens($key_source),
        'store'             => false,
        'text'              => array(
            'format' => array(
                'type' => 'text',
            ),
        ),
    );
}

/**
 * Extracts text output from a Responses API payload.
 *
 * @param array<string, mixed> $body Response body.
 * @return string
 */
function antichrist_engine_foundation_ai_extract_output_text($body)
{
    if (empty($body['output']) || !is_array($body['output'])) {
        return '';
    }

    $chunks = array();

    foreach ($body['output'] as $output_item) {
        if (!is_array($output_item) || empty($output_item['content']) || !is_array($output_item['content'])) {
            continue;
        }

        foreach ($output_item['content'] as $content_item) {
            if (!is_array($content_item) || 'output_text' !== ($content_item['type'] ?? '')) {
                continue;
            }

            $text = trim((string) ($content_item['text'] ?? ''));

            if ($text) {
                $chunks[] = $text;
            }
        }
    }

    return trim(implode("\n\n", $chunks));
}

/**
 * Sends a normalized AI AJAX error.
 *
 * @param string               $code Error code.
 * @param string               $message Error message.
 * @param int                  $status HTTP status.
 * @param array<string, mixed> $extra Extra payload.
 * @return mixed
 */
function antichrist_engine_foundation_ai_send_json_error($code, $message, $status = 400, $extra = array())
{
    return wp_send_json_error(array_merge(array(
        'code'    => sanitize_key($code),
        'message' => (string) $message,
    ), $extra), $status);
}

/**
 * Sends a normalized auth-required AJAX response.
 *
 * @return mixed
 */
function antichrist_engine_foundation_ai_handle_auth_required_ajax()
{
    return antichrist_engine_foundation_ai_send_json_error(
        'auth_required',
        'Sign in before using the AI Engine. The live form is account-gated to protect quota, keys, and abuse controls.',
        401
    );
}

/**
 * Handles AI chat AJAX requests.
 *
 * @return mixed
 */
function antichrist_engine_foundation_ai_handle_chat_ajax()
{
    if (!check_ajax_referer('antichrist_engine_ai', 'nonce', false)) {
        return antichrist_engine_foundation_ai_send_json_error('invalid_nonce', 'The AI request could not be verified. Refresh the page and try again.', 403);
    }

    if (!is_user_logged_in()) {
        return antichrist_engine_foundation_ai_handle_auth_required_ajax();
    }

    $user_id = get_current_user_id();
    $raw_prompt = antichrist_engine_security_get_post_value('prompt');

    if (strlen($raw_prompt) > antichrist_engine_foundation_ai_get_user_key_prompt_limit() + 500) {
        return antichrist_engine_foundation_ai_send_json_error('too_long', 'That prompt is too large for this interface. Shorten it before sending.', 413);
    }

    $prompt = antichrist_engine_foundation_ai_sanitize_plain_text($raw_prompt, antichrist_engine_foundation_ai_get_user_key_prompt_limit() + 1);

    if (!$prompt) {
        return antichrist_engine_foundation_ai_send_json_error('empty', 'Enter a question, belief, or premise before asking the Adversary to respond.', 400);
    }

    $persona_key = sanitize_key(antichrist_engine_security_get_post_value('persona'));
    $protocol_key = antichrist_engine_foundation_ai_normalize_protocol_key(antichrist_engine_security_get_post_value('protocol'));
    $history = antichrist_engine_foundation_ai_sanitize_history(antichrist_engine_security_get_post_value('history'));
    $policy = antichrist_engine_foundation_ai_select_api_key_for_request($prompt, $history, $user_id);

    if ('ok' !== ($policy['status'] ?? '')) {
        return antichrist_engine_foundation_ai_send_json_error(
            (string) ($policy['code'] ?? 'request_blocked'),
            (string) ($policy['message'] ?? 'The AI request cannot be sent with the current key policy.'),
            !empty($policy['key_required']) ? 402 : 413,
            array(
                'keyRequired'  => !empty($policy['key_required']),
                'promptLimit'  => (int) ($policy['prompt_limit'] ?? 0),
                'contextLimit' => (int) ($policy['context_limit'] ?? 0),
            )
        );
    }

    $rate_action = 'user' === ($policy['source'] ?? '') ? 'ai_engine_user_key' : 'ai_engine_site_key';

    if (!antichrist_engine_security_check_rate_limit($rate_action, (int) ($policy['rate_limit'] ?? 3), (int) ($policy['rate_window'] ?? HOUR_IN_SECONDS))) {
        return antichrist_engine_foundation_ai_send_json_error('rate_limited', 'Too many AI requests were received from this account or network. Please wait and try again.', 429);
    }

    $payload = antichrist_engine_foundation_ai_build_response_payload($prompt, $history, $persona_key, (string) ($policy['source'] ?? 'site'), $protocol_key);
    $response = wp_remote_post('https://api.openai.com/v1/responses', array(
        'timeout' => 45,
        'headers' => array(
            'Content-Type'  => 'application/json',
            'Authorization' => 'Bearer ' . (string) ($policy['api_key'] ?? ''),
        ),
        'body'    => wp_json_encode($payload),
    ));

    if (is_wp_error($response) || 200 !== (int) wp_remote_retrieve_response_code($response)) {
        return antichrist_engine_foundation_ai_send_json_error('request_failed', 'The AI engine could not complete the request just now. Please try again shortly.', 502);
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);
    $answer = is_array($body) ? antichrist_engine_foundation_ai_extract_output_text($body) : '';

    if (!$answer) {
        return antichrist_engine_foundation_ai_send_json_error('empty_response', 'The AI engine returned an empty response. Try rephrasing the prompt.', 502);
    }

    return wp_send_json_success(array(
        'answer'          => $answer,
        'message'         => 'Response received.',
        'model'           => antichrist_engine_foundation_ai_get_model(),
        'keySource'       => (string) ($policy['source'] ?? 'site'),
        'persona'         => sanitize_key($persona_key ?: antichrist_engine_foundation_ai_get_default_persona_key()),
        'protocol'        => $protocol_key,
        'maxOutputTokens' => (int) ($policy['max_output_tokens'] ?? 0),
    ));
}
add_action('wp_ajax_antichrist_engine_ai_chat', 'antichrist_engine_foundation_ai_handle_chat_ajax');
add_action('wp_ajax_nopriv_antichrist_engine_ai_chat', 'antichrist_engine_foundation_ai_handle_auth_required_ajax');

/**
 * Handles encrypted personal-key AJAX requests.
 *
 * @return mixed
 */