我正在尝试使用 ChatGPT 通过短代码编写博客文章的各个部分。目标是添加 [prompt="write a section about bikes"] 并获取有关自行车的部分。
但是,我在 WordPress 网站的前端不断收到一般性回复,“您好,今天我能为您提供什么帮助?”
我知道我力不从心,但我觉得这应该行得通。
/**
* ChatGPT Shortcode Handler
*/
function get_chatgpt_response($messages, $cache_reset) {
$api_url = 'https://api.openai.com/v1/chat/completions';
$api_key = 'My API Key';
$hash = md5(serialize($messages));
// Check if the response is cached in the WordPress database
$cached_response = get_transient('chatgpt_response_' . $hash);
if ($cached_response !== false && $cached_response !== '' && strpos($cached_response, '<p>') !== false && $cache_reset == 0) {
echo "<!-- true -->";
return $cached_response;
}
$data = array(
'model' => 'gpt-3.5-turbo',
'messages' => $messages,
'max_tokens' => 1024,
'temperature' => 0.7
);
$payload = json_encode($data);
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer '.$api_key
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
$chatgpt_response = $result['choices'][0]['message']['content'];
// Cache the response in the WordPress database for 1 hour
set_transient('chatgpt_response_' . $hash, $chatgpt_response, HOUR_IN_SECONDS);
return $chatgpt_response;
}
/**
* ChatGPT Shortcode Handler
*/
function chatgpt_shortcode_handler($atts) {
$atts = shortcode_atts(array(
'prompt' => '',
), $atts, 'prompt');
// Get the prompt value from the shortcode attribute
$prompt = sanitize_text_field($atts['prompt']);
// Generate a unique cache key based on the prompt
$cache_key = 'chatgpt_' . md5($prompt);
// Check if the response is already cached
$cached_response = get_transient($cache_key);
if ($cached_response !== false && $cached_response !== '' && strpos($cached_response, '<p>') !== false) {
return $cached_response;
}
$messages = array(
array(
'role' => 'system',
'content' => 'You: ' . $prompt,
),
);
// Set the cache reset flag to 0 to avoid resetting the cache
$cache_reset = 0;
// Make API request to ChatGPT and retrieve the generated content
$chatgpt_response = get_chatgpt_response($messages, $cache_reset);
// Cache the response in the WordPress database for 1 hour
set_transient($cache_key, $chatgpt_response, HOUR_IN_SECONDS);
// Return the generated content
return wpautop($chatgpt_response);
}
add_shortcode('prompt', 'chatgpt_shortcode_handler');