hooks.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace IROChatGPT {
  3. use HaoZiTeam\ChatGPT\V2 as ChatGPTV2;
  4. use WP_Post;
  5. define('MAX_MESSAGE_LENGTH', 4096);
  6. define("DEFAULT_INIT_PROMPT", "You are a excerpt generator. " .
  7. "You can summarize articles given their title and full text. " .
  8. "You should use the same language as the article for your excerpt. " .
  9. "You do not need to write in third person.");
  10. define('DEFAULT_ASK_PROMPT', "Please summarize articles provided before.");
  11. define('POST_METADATA_KEY', "ai_summon_excerpt");
  12. /**
  13. * 调用ChatGPT API生成指定文章的摘要并返回
  14. */
  15. function summon_article_excerpt(WP_Post $post)
  16. {
  17. $chatGPT = new ChatGPTV2(iro_opt('chatgpt_access_token'), iro_opt('chatgpt_base_url'));
  18. $chatGPT->addMessage(iro_opt('chatgpt_init_prompt', DEFAULT_INIT_PROMPT), 'system');
  19. $chatGPT->addMessage("文章标题:" . $post->post_title, 'user');
  20. $content = $post->post_content;
  21. $content = substr(wp_strip_all_tags(apply_filters('the_content', $content)), 0, 4050);
  22. $chatGPT->addMessage("正文:" . $content, 'user');
  23. $answer = '';
  24. foreach ($chatGPT->ask(iro_opt('chatgpt_ask_prompt', DEFAULT_ASK_PROMPT)) as $item) {
  25. $answer .= $item['answer'];
  26. }
  27. return $answer;
  28. }
  29. function apply_chatgpt_hook()
  30. {
  31. if (iro_opt('chatgpt_article_summarize')) {
  32. add_action('save_post_post', function (int $post_id, WP_Post $post, bool $update) {
  33. if (!has_excerpt($post_id)) {
  34. try {
  35. $excerpt = summon_article_excerpt($post);
  36. update_post_meta($post_id, POST_METADATA_KEY, $excerpt);
  37. } catch (\Throwable $th) {
  38. //throw $th;
  39. error_log('ChatGPT-excerpt-err:' . $th);
  40. }
  41. }
  42. }, 10, 3);
  43. add_filter('the_excerpt', function (string $post_excerpt) {
  44. global $post;
  45. if (has_excerpt($post)) {
  46. return $post_excerpt;
  47. } else {
  48. $ai_excerpt = get_post_meta($post->ID, POST_METADATA_KEY, true);
  49. return $ai_excerpt ? $ai_excerpt : $post_excerpt;
  50. }
  51. });
  52. }
  53. }
  54. }