WordPress集成ChatGPT插件开发与API调用频率限制解决方案

ChatGPT API基础配置

要开始WordPress集成ChatGPT插件开发,首先需要获取OpenAI API密钥。登录OpenAI官方网站后,进入API密钥管理页面创建新密钥。请妥善保存此密钥,它将在后续所有API调用中使用。

WordPress插件中,API密钥的存储应当采用安全方式。以下是基础配置类的实现:


class ChatGPT_API_Config {
    private $api_key;
    private $api_endpoint = 'https://api.openai.com/v1/chat/completions';
    private $model = 'gpt-3.5-turbo';
    private $max_tokens = 1000;
    private $temperature = 0.7;
    
    public function __construct($api_key) {
        $this->api_key = $api_key;
    }
    
    public function set_model($model) {
        $this->model = $model;
        return $this;
    }
    
    public function set_max_tokens($tokens) {
        $this->max_tokens = intval($tokens);
        return $this;
    }
    
    public function set_temperature($temp) {
        $this->temperature = floatval($temp);
        return $this;
    }
}

温度参数(temperature)控制输出随机性,值越低输出越确定,值越高输出越随机。对于需要一致性回答的场景,建议设置为0.2-0.5;对于创意性内容,可设置为0.7-1.0。

WordPress插件结构设计

一个标准的WordPress插件需要遵循特定的文件结构。创建一个名为"wp-chatgpt-integration"的文件夹,内部包含以下文件:


wp-chatgpt-integration/
├── wp-chatgpt-integration.php     主插件文件
├── includes/
│   ├── class-api-handler.php      API请求处理类
│   ├── class-admin-settings.php   管理设置页面
│   └── class-content-generator.php  内容生成器
├── assets/
│   ├── css/
│   │   └── admin-style.css         管理界面样式
│   └── js/
│       └── admin-script.js         管理界面脚本
└── README.md                       插件说明文档

主插件文件wp-chatgpt-integration.php需要包含插件头部信息,用于WordPress识别:


/
  Plugin Name: WordPress ChatGPT Integration
  Plugin URI: https://example.com/wp-chatgpt-integration
  Description: Integrates ChatGPT with WordPress for content generation.
  Version: 1.0.0
  Author: Your Name
  Author URI: https://example.com
  License: GPL v2 or later
  License URI: https://www.gnu.org/licenses/gpl-2.0.
  Text Domain: wp-chatgpt
  Domain Path: /languages
 /

// 如果直接访问此文件,则中止执行
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('WP_CHATGPT_VERSION', '1.0.0');
define('WP_CHATGPT_PATH', plugin_dir_path(__FILE__));
define('WP_CHATGPT_URL', plugin_dir_url(__FILE__));

// 加载插件功能
function wp_chatgpt_init() {
    // 包含必要的文件
    require_once WP_CHATGPT_PATH . 'includes/class-api-handler.php';
    require_once WP_CHATGPT_PATH . 'includes/class-admin-settings.php';
    require_once WP_CHATGPT_PATH . 'includes/class-content-generator.php';
    
    // 实例化管理设置类
    new WP_ChatGPT_Admin_Settings();
    
    // 实例化内容生成器
    new WP_ChatGPT_Content_Generator();
}
add_action('plugins_loaded', 'wp_chatgpt_init');

API调用频率限制处理

OpenAI API对调用频率有限制,免费账户每分钟最多请求3次,每分钟最多处理4096个token。付费账户限制更高,但仍需合理控制请求频率。以下是实现API请求队列和频率限制的代码:


class WP_ChatGPT_API_Queue {
    private $queue = array();
    private $last_request_time = 0;
    private $min_interval = 20; // 请求间隔时间(秒)
    private $max_retries = 3;   // 最大重试次数
    
    public function add_request($prompt, $callback) {
        $this->queue[] = array(
            'prompt' => $prompt,
            'callback' => $callback,
            'attempts' => 0
        );
        
        // 如果没有正在处理的请求,立即开始处理队列
        if (count($this->queue) === 1) {
            $this->process_queue();
        }
    }
    
    private function process_queue() {
        if (empty($this->queue)) {
            return;
        }
        
        $current_time = time();
        $time_since_last_request = $current_time - $this->last_request_time;
        
        // 确保请求间隔
        if ($time_since_last_request min_interval) {
            $delay = ($this->min_interval - $time_since_last_request)  1000;
            wp_schedule_single_event(time() + $delay, 'wp_chatgpt_process_queue');
            return;
        }
        
        $request = &$this->queue[0];
        $request['attempts']++;
        
        try {
            $api_handler = new WP_ChatGPT_API_Handler();
            $response = $api_handler->send_request($request['prompt']);
            
            // 调用回调函数处理响应
            call_user_func($request['callback'], $response);
            
            // 从队列中移除已处理的请求
            array_shift($this->queue);
            $this->last_request_time = time();
            
            // 处理下一个请求
            $this->process_queue();
        } catch (Exception $e) {
            // 如果重试次数未超过限制,将请求重新加入队列
            if ($request['attempts'] max_retries) {
                // 将当前请求移到队列末尾
                $failed_request = array_shift($this->queue);
                array_push($this->queue, $failed_request);
                
                // 延迟后重试
                wp_schedule_single_event(time() + 30, 'wp_chatgpt_process_queue');
            } else {
                // 超过重试次数,记录错误并移除请求
                error_log('ChatGPT API request failed after ' . $this->max_retries . ' attempts: ' . $e->getMessage());
                array_shift($this->queue);
                
                // 处理下一个请求
                $this->process_queue();
            }
        }
    }
}

频率限制处理的关键在于:
1. 记录每次API请求的时间戳
2. 计算与上次请求的时间间隔
3. 如果间隔小于最小间隔时间,延迟处理
4. 实现请求失败后的重试机制
5. 避免因频繁请求导致API限制

功能实现与代码示例

现在实现核心的API请求处理类,用于与ChatGPT API通信:


class WP_ChatGPT_API_Handler {
    private $api_key;
    private $api_endpoint = 'https://api.openai.com/v1/chat/completions';
    
    public function __construct() {
        $this->api_key = get_option('wp_chatgpt_api_key', '');
    }
    
    public function send_request($prompt, $model = 'gpt-3.5-turbo', $max_tokens = 1000, $temperature = 0.7) {
        if (empty($this->api_key)) {
            throw new Exception('API key is not configured.');
        }
        
        $headers = array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $this->api_key
        );
        
        $body = array(
            'model' => $model,
            'messages' => array(
                array(
                    'role' => 'user',
                    'content' => $prompt
                )
            ),
            'max_tokens' => intval($max_tokens),
            'temperature' => floatval($temperature)
        );
        
        $response = wp_remote_post($this->api_endpoint, array(
            'headers' => $headers,
            'body' => json_encode($body),
            'timeout' => 30,
            'sslverify' => true
        ));
        
        if (is_wp_error($response)) {
            throw new Exception('API request failed: ' . $response->get_error_message());
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = json_decode(wp_remote_retrieve_body($response), true);
        
        if ($response_code !== 200) {
            $error_message = isset($response_body['error']['message']) ? $response_body['error']['message'] : 'Unknown error';
            throw new Exception('API error (' . $response_code . '): ' . $error_message);
        }
        
        if (!isset($response_body['choices'][0]['message']['content'])) {
            throw new Exception('Invalid API response structure.');
        }
        
        return $response_body['choices'][0]['message']['content'];
    }
}

接下来,实现内容生成器类,用于在WordPress中创建ChatGPT生成的内容:


class WP_ChatGPT_Content_Generator {
    private $api_handler;
    private $queue;
    
    public function __construct() {
        $this->api_handler = new WP_ChatGPT_API_Handler();
        $this->queue = new WP_ChatGPT_API_Queue();
        
        // 添加AJAX处理
        add_action('wp_ajax_generate_content', array($this, 'ajax_generate_content'));
        add_action('wp_ajax_nopriv_generate_content', array($this, 'ajax_generate_content'));
        
        // 添加元框到文章编辑页面
        add_action('add_meta_boxes', array($this, 'add_meta_box'));
        
        // 保存文章时处理生成的内容
        add_action('save_post', array($this, 'save_generated_content'), 10, 2);
    }
    
    public function add_meta_box() {
        add_meta_box(
            'chatgpt_content_generator',
            'ChatGPT Content Generator',
            array($this, 'render_meta_box'),
            'post',
            'normal',
            'high'
        );
    }
    
    public function render_meta_box($post) {
        wp_nonce_field('chatgpt_generate_content', 'chatgpt_nonce');
        ?>
        


GPT-3.5 Turbo GPT-4

jQuery(document).ready(function($) { $('generate_content').on('click', function() { var prompt = $('chatgpt_prompt').val(); var model = $('chatgpt_model').val(); var max_tokens = $('chatgpt_max_tokens').val(); var temperature = $('chatgpt_temperature').val(); if (!prompt) { alert(''); return; } $('generation_status').(''); $('generate_content').prop('disabled', true); $.ajax({ url: ajaxurl, type: 'POST', data: { action: 'generate_content', prompt: prompt, model: model, max_tokens: max_tokens, temperature: temperature, nonce: '' }, success: function(response) { if (response.success) { $('generated_text').val(response.data); $('generated_content').show(); } else { alert(response.data); } $('generation_status').(''); $('generate_content').prop('disabled', false); }, error: function() { alert(''); $('generation_status').(''); $('generate_content').prop('disabled', false); } }); }); $('insert_content').on('click', function() { var content = $('generated_text').val(); if (window.tinymce && window.tinymce.activeEditor) { window.tinymce.activeEditor.execCommand('mceInsertContent', false, content); } else { $('content').val($('content').val() + content); } }); }); api_handler->send_request($prompt, $model, $max_tokens, $temperature); wp_send_json_success($content); } catch (Exception $e) { wp_send_json_error($e->getMessage()); } } public function save_generated_content($post_id, $post) { if (!isset($_POST['chatgpt_nonce']) || !wp_verify_nonce($_POST['chatgpt_nonce'], 'chatgpt_generate_content')) { return; } if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } if (!current_user_can('edit_post', $post_id)) { return; } if (isset($_POST['chatgpt_generated_content'])) { $generated_content = wp_kses_post($_POST['chatgpt_generated_content']); update_post_meta($post_id, '_chatgpt_generated_content', $generated_content); } } }

测试与调试方法

在WordPress插件开发过程中,测试和调试是必不可少的环节。以下是针对ChatGPT集成插件的测试和调试方法:

首先,启用WordPress调试模式,在wp-config.php文件中添加以下代码:


// 启用调试模式
define('WP_DEBUG', true);
// 启用调试日志记录
define('WP_DEBUG_LOG', true);
// 禁用前端错误显示
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors', 0);

创建一个测试类,用于验证API连接和功能:


class WP_ChatGPT_Tests {
    private $api_handler;
    
    public function __construct() {
        $this->api_handler = new WP_ChatGPT_API_Handler();
        
        // 添加管理页面测试选项
        add_action('admin_menu', array($this, 'add_test_page'));
    }
    
    public function add_test_page() {
        add_submenu_page(
            'options-general.php',
            'ChatGPT Integration Tests',
            'ChatGPT Tests',
            'manage_options',
            'wp-chatgpt-tests',
            array($this, 'render_test_page')
        );
    }
    
    public function render_test_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        $test_results = array();
        
        // 如果提交了测试表单
        if (isset($_POST['run_tests']) && check_admin_referer('chatgpt_tests')) {
            $test_results = $this->run_all_tests();
        }
        ?>
        

ChatGPT Integration Tests

WordPress集成ChatGPT插件开发与API调用频率限制解决方案

Test Results

Test Status Details
✓ Passed ✗ Failed Error:
test_api_key_config(); // 测试2: API连接 $results[] = $this->test_api_connection(); // 测试3: 内容生成 $results[] = $this->test_content_generation(); // 测试4: 频率限制处理 $results[] = $this->test_rate_limiting(); // 测试5: 错误处理 $results[] = $this->test_error_handling(); return $results; } private function test_api_key_config() { $api_key = get_option('wp_chatgpt_api_key', ''); if (empty($api_key)) { return array( 'name' => 'API Key Configuration', 'success' => false, 'message' => 'API key is not configured in settings.' ); } if (!preg_match('/^sk-[a-zA-Z0-9]+$/', $api_key)) { return array( 'name' => 'API Key Configuration', 'success' => false, 'message' => 'API key format is invalid.' ); } return array( 'name' => 'API Key Configuration', 'success' => true, 'message' => 'API key is properly configured.' ); } private function test_api_connection() { try { $response = $this->api_handler->send_request('Test', 'gpt-3.5-turbo', 10, 0.5); if (empty($response)) { return array( 'name' => 'API Connection', 'success' => false, 'message' => 'API returned empty response.' ); } return array( 'name' => 'API Connection', 'success' => true, 'message' => 'Successfully connected to API and received response.' ); } catch (Exception $e) { return array( 'name' => 'API Connection', 'success' => false, 'message' => $e->getMessage() ); } } private function test_content_generation() { try { $prompt = 'Generate a short paragraph about WordPress.'; $response = $this->api_handler->send_request($prompt, 'gpt-3.5-turbo', 100, 0.7); if (empty($response)) { return array( 'name' => 'Content Generation', 'success' => false, 'message' => 'Generated content is empty.' ); } if (strlen($response) 'Content Generation', 'success' => false, 'message' => 'Generated content is too short.' ); } return array( 'name' => 'Content Generation', 'success' => true, 'message' => 'Successfully generated content: ' . substr($response, 0, 50) . '...' ); } catch (Exception $e) { return array( 'name' => 'Content Generation', 'success' => false, 'message' => $e->getMessage() ); } } private function test_rate_limiting() { // 这个测试需要模拟多个快速请求 // 在实际环境中,这可能需要特殊处理以避免触发真正的API限制 try { $queue = new WP_ChatGPT_API_Queue(); $test_results = array(); $callback = function($response) use (&$test_results) { $test_results[] = $response; }; // 添加多个请求到队列 for ($i = 0; $i add_request("Test request $i", $callback); } // 等待队列处理完成 $attempts = 0; while (count($test_results) < 3 && $attempts < 10) { sleep(1); $attempts++; } if (count($test_results) 'Rate Limiting', 'success' => false, 'message' => 'Queue processing timed out.' ); } return array( 'name' => 'Rate Limiting', 'success' => true, 'message' => 'Successfully processed ' . count($test_results) . ' queued requests.' ); } catch (Exception $e) { return array( 'name' => 'Rate Limiting', 'success' => false, 'message' => $e->getMessage() ); } } private function test_error_handling() { try { // 测试无效API密钥 $original_key = get_option('wp_chatgpt_api_key', ''); update_option('wp_chatgpt_api_key', 'invalid-key'); $temp_handler = new WP_ChatGPT_API_Handler(); try { $temp_handler->send_request('Test', 'gpt-3.5-turbo', 10, 0.5); // 恢复原始API密钥 update_option('wp_chatgpt_api_key', $original_key); return array( 'name' => 'Error Handling', 'success' => false, 'message' => 'API did not reject invalid API key.' ); } catch (Exception $e) { // 恢复原始API密钥 update_option('wp_chatgpt_api_key', $original_key); if (strpos($e->getMessage(), 'API key') !== false) { return array( 'name' => 'Error Handling', 'success' => true, 'message' => 'Correctly handled invalid API key error.' ); } else { return array( 'name' => 'Error Handling', 'success' => false, 'message' => 'API returned unexpected error: ' . $e->getMessage() ); } } } catch (Exception $e) { return array( 'name' => 'Error Handling', 'success' => false, 'message' => 'Test setup failed: ' . $e->getMessage() ); } } }

在测试过程中,注意以下几点:
1. 测试API连接时,使用最小化的token数量,以避免不必要的API调用成本
2. 测试频率限制时,确保不会触发真实的API限制,导致账户临时封禁
3. 错误处理测试后,务必恢复原始配置
4. 在生产环境中,禁用测试页面和调试代码,避免安全隐患