| 1 |
<?php |
| 2 |
/** |
| 3 |
* AiGuardrails — Rate limiting and spend guardrails for AI Copilot. |
| 4 |
* |
| 5 |
* @package WPFunnels\AI\Telemetry |
| 6 |
* @since 3.13.0 |
| 7 |
*/ |
| 8 |
|
| 9 |
namespace WPFunnels\AI\Telemetry; |
| 10 |
|
| 11 |
defined( 'ABSPATH' ) || exit; |
| 12 |
|
| 13 |
use WP_Error; |
| 14 |
|
| 15 |
/** |
| 16 |
* Class AiGuardrails |
| 17 |
*/ |
| 18 |
class AiGuardrails { |
| 19 |
|
| 20 |
/** |
| 21 |
* Max requests per minute per user. |
| 22 |
*/ |
| 23 |
const MAX_REQUESTS_PER_MINUTE = 30; |
| 24 |
|
| 25 |
/** |
| 26 |
* Max turn budget per agent loop run. |
| 27 |
*/ |
| 28 |
const MAX_TURN_BUDGET = 25; |
| 29 |
|
| 30 |
/** |
| 31 |
* Check rate limit for current user. |
| 32 |
* |
| 33 |
* @param int $user_id User ID. |
| 34 |
* @return true|\WP_Error |
| 35 |
*/ |
| 36 |
public static function checkRateLimit( $user_id = 0 ) { |
| 37 |
if ( ! $user_id ) { |
| 38 |
$user_id = function_exists( 'get_current_user_id' ) ? get_current_user_id() : 0; |
| 39 |
} |
| 40 |
|
| 41 |
$transient_key = 'wpfnl_ai_rate_' . $user_id; |
| 42 |
$count = (int) get_transient( $transient_key ); |
| 43 |
|
| 44 |
if ( $count >= self::MAX_REQUESTS_PER_MINUTE ) { |
| 45 |
return new WP_Error( |
| 46 |
'rate_limit_exceeded', |
| 47 |
__( 'Rate limit exceeded. Please wait a moment before sending more AI requests.', 'wpfnl' ), |
| 48 |
[ 'status' => 429 ] |
| 49 |
); |
| 50 |
} |
| 51 |
|
| 52 |
set_transient( $transient_key, $count + 1, MINUTE_IN_SECONDS ); |
| 53 |
return true; |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Record token usage for telemetry tracking. |
| 58 |
* |
| 59 |
* @param int $input_tokens Input tokens. |
| 60 |
* @param int $output_tokens Output tokens. |
| 61 |
* @param string $provider Provider slug. |
| 62 |
* @return void |
| 63 |
*/ |
| 64 |
public static function recordUsage( $input_tokens, $output_tokens, $provider = 'openai' ) { |
| 65 |
$total = (int) get_option( 'wpfnl_ai_total_tokens_used', 0 ); |
| 66 |
update_option( 'wpfnl_ai_total_tokens_used', $total + $input_tokens + $output_tokens ); |
| 67 |
|
| 68 |
do_action( 'wpfunnels_ai_usage_recorded', [ |
| 69 |
'input_tokens' => $input_tokens, |
| 70 |
'output_tokens' => $output_tokens, |
| 71 |
'provider' => $provider, |
| 72 |
] ); |
| 73 |
} |
| 74 |
} |
| 75 |
|