1
0

hooks.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace IROChatGPT {
  3. use Exception;
  4. use Orhanerday\OpenAi\OpenAi;
  5. use WP_Post;
  6. define("DEFAULT_INIT_PROMPT", "请以作者的身份,以激发好奇吸引阅读为目的,结合文章核心观点来提取的文章中最吸引人的内容,为以下文章编写一个用词精炼简短、110字以内、与文章语言一致的引言。");
  7. define("DEFAULT_MODEL", "gpt-3.5-turbo");
  8. define('POST_METADATA_KEY', "ai_summon_excerpt");
  9. function apply_chatgpt_hook()
  10. {
  11. if (iro_opt('chatgpt_article_summarize')) {
  12. $exclude_ids = iro_opt('chatgpt_exclude_ids', '');
  13. add_action('save_post_post', function (int $post_id, WP_Post $post, bool $update) use ($exclude_ids) {
  14. if (!has_excerpt($post_id) && !in_array($post_id, explode(",", $exclude_ids), false)) {
  15. try {
  16. $excerpt = summon_article_excerpt($post);
  17. update_post_meta($post_id, POST_METADATA_KEY, $excerpt);
  18. } catch (\Throwable $th) {
  19. error_log('ChatGPT-excerpt-err:' . $th);
  20. }
  21. }
  22. }, 10, 3);
  23. add_filter('the_excerpt', function (string $post_excerpt) {
  24. global $post;
  25. if (has_excerpt($post)) {
  26. return $post_excerpt;
  27. } else {
  28. $ai_excerpt = get_post_meta($post->ID, POST_METADATA_KEY, true);
  29. return $ai_excerpt ? $ai_excerpt : $post_excerpt;
  30. }
  31. });
  32. }
  33. }
  34. function summon_article_excerpt(WP_Post $post)
  35. {
  36. $chatGPT_base_url = iro_opt('chatgpt_base_url');
  37. $chatGPT_access_token = iro_opt('chatgpt_access_token');
  38. $chatGPT_prompt_init = iro_opt('chatgpt_init_prompt', DEFAULT_INIT_PROMPT);
  39. $chatGPT_model = iro_opt('chatgpt_model', DEFAULT_MODEL);
  40. if (empty($chatGPT_base_url) || empty($chatGPT_access_token) || empty($chatGPT_prompt_init) || empty($chatGPT_model)) {
  41. throw new Exception("Missing required ChatGPT configuration.");
  42. }
  43. $open_ai = new OpenAi($chatGPT_access_token);
  44. if (str_ends_with($chatGPT_base_url, '/')) {
  45. $chatGPT_base_url = substr($chatGPT_base_url, 0, -1);
  46. }
  47. $open_ai->setBaseURL($chatGPT_base_url);
  48. $chat = $open_ai->chat([
  49. "model" => $chatGPT_model,
  50. "messages" => [
  51. [
  52. "role" => "system",
  53. "content" => $chatGPT_prompt_init
  54. ],
  55. [
  56. "role" => "user",
  57. "content" => "Title: " . $post->post_title
  58. ],
  59. [
  60. "role" => "user",
  61. "content" => "Context: " . mb_substr(preg_replace("/(\\s)\\s{2,}/", "$1",wp_strip_all_tags(apply_filters('the_content', $post->post_content))), 0, 4050)
  62. ],
  63. ]
  64. ]);
  65. $decoded_chat = json_decode($chat);
  66. if (is_null($decoded_chat) || isset($decoded_chat->error)) {
  67. throw new Exception("ChatGPT error: " . json_encode($decoded_chat));
  68. }
  69. return $decoded_chat->choices[0]->message->content;
  70. }
  71. }