hot_keys_generate.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from applications.api import AsyncElasticSearchClient
  2. from applications.api import fetch_deepseek_completion
  3. class HotKeysGenerate:
  4. def __init__(self, pool, log_client, trace_id):
  5. self.elastic_client = AsyncElasticSearchClient()
  6. self.pool = pool
  7. self.log_client = log_client
  8. self.trace_id = trace_id
  9. @staticmethod
  10. async def generate_prompt(formated_titles):
  11. """
  12. 生成热键的prompt
  13. """
  14. prompt = f"""
  15. 请你根据以下的热点时事,帮我生成一些热搜词组,我需要用这些词组来搜索相关的文章。
  16. 生成的每个词组不能太短,需要能够覆盖热点时事的主要内容。如果遇到相似的热点时事,需要合并为一个词组。
  17. 如果遇到敏感话题,直接过滤掉即可
  18. ## 输入
  19. {formated_titles}
  20. ## 输出
  21. 输出要求是 JSON 格式,返回一个数组,数组中的每个元素都是一个字符串,字符串是一个热搜词组。
  22. 参考结构:{{
  23. "hot_keys": ["key1", "key2", "key3", ...]
  24. }}
  25. """
  26. return prompt
  27. async def get_hot_titles(self):
  28. query = """
  29. SELECT title FROM hot_point_titles WHERE useful = 2
  30. AND create_time > DATE_SUB(CURDATE(), INTERVAL 3 DAY)
  31. ;
  32. """
  33. response = await self.pool.async_fetch(query=query)
  34. hot_titles = [item["title"] for item in response if '习近平' not in item['title']]
  35. return "\n".join(hot_titles)
  36. async def deal(self):
  37. article_id_set = set()
  38. hot_titles = await self.get_hot_titles()
  39. prompt = await self.generate_prompt(hot_titles)
  40. completion = fetch_deepseek_completion(model="default", prompt=prompt, output_type="json")
  41. hot_keys = completion["hot_keys"]
  42. if not hot_keys:
  43. return list(article_id_set)
  44. for key in hot_keys:
  45. response = await self.elastic_client.search(
  46. search_keys=key
  47. )
  48. for item in response[:5]:
  49. article_id_set.add(item["article_id"])
  50. return list(article_id_set)