report.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. """
  2. 报告生成模块
  3. 根据研究结果生成结构化报告
  4. """
  5. from typing import Dict, List, Any, Optional
  6. import logging
  7. from backend.utils.api_client import LLMClient
  8. from backend.config import REPORT_MAX_LENGTH, REPORT_TEMPERATURE
  9. logger = logging.getLogger(__name__)
  10. class ReportGenerator:
  11. """研究报告生成器"""
  12. def __init__(self):
  13. self.llm_client = LLMClient()
  14. async def generate_report(
  15. self,
  16. research_intent: str,
  17. keywords: List[str],
  18. papers: List[Dict[str, Any]],
  19. clusters: Optional[Dict[str, Any]] = None,
  20. max_length: int = REPORT_MAX_LENGTH,
  21. temperature: float = REPORT_TEMPERATURE
  22. ) -> Dict[str, Any]:
  23. """
  24. 生成研究报告
  25. Args:
  26. research_intent: 用户的研究意图
  27. keywords: 提取的关键词
  28. papers: 检索到的论文
  29. clusters: 聚类结果
  30. max_length: 报告最大长度
  31. temperature: 生成参数
  32. Returns:
  33. 包含报告内容的字典
  34. """
  35. try:
  36. # 1. 准备论文信息
  37. paper_info = []
  38. for i, paper in enumerate(papers[:10]): # 只使用前10篇
  39. paper_info.append(
  40. f"{i+1}. {paper['title']} ({', '.join(paper['authors'][:3])})"
  41. f"\n摘要: {paper['summary'][:300]}..."
  42. )
  43. paper_text = "\n\n".join(paper_info)
  44. # 2. 准备聚类信息
  45. cluster_text = ""
  46. if clusters and "cluster_info" in clusters:
  47. for cluster_id, info in clusters["cluster_info"].items():
  48. papers_in_cluster = info["papers"]
  49. if papers_in_cluster:
  50. titles = [p["title"] for p in papers_in_cluster[:3]]
  51. cluster_text += f"聚类 {cluster_id+1} (包含 {len(papers_in_cluster)} 篇论文):\n"
  52. cluster_text += "代表性论文: " + "; ".join(titles) + "\n\n"
  53. # 3. 构造提示
  54. cluster_section = f"## 文献聚类\n{cluster_text}" if cluster_text else ""
  55. prompt = f"""
  56. 作为一位科研助手,请基于以下信息为研究主题生成一份结构化的调研报告。
  57. ## 研究主题
  58. {research_intent}
  59. ## 关键词
  60. {', '.join(keywords)}
  61. ## 检索到的文献
  62. {paper_text}
  63. {cluster_section}
  64. 请生成一份完整的调研报告,包括以下部分:
  65. 1. 研究背景与意义(简要介绍该领域的重要性和研究现状)
  66. 2. 研究方向分析(基于文献聚类识别主要研究方向)
  67. 3. 关键技术与方法(总结该领域的主要技术和方法论)
  68. 4. 代表性研究工作(列举2-3项代表性研究及其贡献)
  69. 5. 未来研究展望(分析领域挑战与未来可能的突破点)
  70. 报告应当学术严谨、结构清晰、信息准确。长度控制在1000-1500字。
  71. """
  72. # 4. 生成报告
  73. logger.info("Generating research report")
  74. report_content = await self.llm_client.generate_text(
  75. prompt=prompt,
  76. temperature=temperature,
  77. max_tokens=max_length
  78. )
  79. # 5. 构造结果
  80. report = {
  81. "research_intent": research_intent,
  82. "content": report_content,
  83. "keywords": keywords,
  84. "paper_count": len(papers)
  85. }
  86. return report
  87. except Exception as e:
  88. logger.error(f"Report generation error: {str(e)}", exc_info=True)
  89. return {
  90. "research_intent": research_intent,
  91. "content": f"报告生成失败: {str(e)}",
  92. "error": str(e)
  93. }