{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 智能论文助手 (PaperAssistant)\n", "\n", "## 📝 项目简介\n", "\n", "基于 HelloAgents 框架的多智能体论文助手,支持文献检索、论文总结、引用生成、论文润色和大纲生成。\n", "\n", "### 作者信息\n", "- 姓名: chengH425\n", "- GitHub: @chengH425\n", "- 日期: 2026-07-20" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 第1部分:环境配置" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 安装依赖(如已安装可跳过)\n", "# !pip install -q hello-agents python-dotenv" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 导入核心库\n", "import os\n", "import sys\n", "import json\n", "from datetime import datetime\n", "from typing import Dict, Any, List\n", "\n", "# Windows 控制台 UTF-8 编码兼容\n", "sys.stdout.reconfigure(encoding='utf-8')\n", "\n", "from dotenv import load_dotenv\n", "from hello_agents import (\n", " HelloAgentsLLM, SimpleAgent, ReflectionAgent,\n", " PlanSolveAgent, ToolRegistry, Config\n", ")\n", "from hello_agents.tools import Tool, ToolParameter, ToolResponse, ToolStatus\n", "\n", "# 加载环境变量\n", "load_dotenv()\n", "\n", "print(\"环境配置完成!\")\n", "print(f\" LLM Model: {os.getenv('LLM_MODEL_ID', 'Qwen/Qwen2.5-72B-Instruct')}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 第2部分:工具定义" ] }, { "cell_type": "code", "execution_count": null, "id": "ac29f814", "metadata": {}, "outputs": [], "source": "# 从 src/ 模块导入自定义工具(9 个工具)\nfrom src.citation_tool import CitationTool\nfrom src.literature_tool import LiteratureSearchTool\nfrom src.aminer_tool import AminerSearchTool\nfrom src.openalex_tool import OpenAlexSearchTool\nfrom src.pubmed_tool import PubMedSearchTool\nfrom src.crossref_tool import CrossRefSearchTool\nfrom src.arxiv_tool import ArxivSearchTool\nfrom src.pdf_tool import PDFExtractTool\n\n# 文本统计分析工具(轻量级,直接定义)\nclass TextAnalysisTool(Tool):\n \"\"\"文本统计分析工具\"\"\"\n def __init__(self):\n super().__init__(\n name=\"text_analysis\",\n description=\"分析文本的统计信息:字数、段落数、句子数等。\"\n )\n def run(self, parameters: Dict[str, Any]) -> ToolResponse:\n text = parameters.get(\"text\", \"\")\n if not text:\n return ToolResponse.error(code=\"INVALID_PARAM\", message=\"文本不能为空\")\n chinese_chars = sum(1 for c in text if '一' <= c <= '鿿')\n english_words = len([w for w in text.split() if any(c.isalpha() for c in w)])\n sentences_cn = len([s for s in text.replace('!', '。').replace('?', '。').split('。') if s.strip()])\n sentences_en = len([s for s in text.replace('!', '.').replace('?', '.').split('.') if s.strip()])\n paragraphs = len([p for p in text.split('\\n') if p.strip()])\n result = {\n \"总字符数\": len(text), \"中文字符数\": chinese_chars,\n \"英文单词数\": english_words, \"句子数(中)\": sentences_cn,\n \"句子数(英)\": sentences_en, \"段落数\": paragraphs,\n \"预估阅读时间(分钟)\": round((chinese_chars / 400 + english_words / 200), 1)\n }\n return ToolResponse.success(\n text=json.dumps(result, ensure_ascii=False, indent=2), data=result)\n def get_parameters(self) -> List[ToolParameter]:\n return [ToolParameter(name=\"text\", type=\"string\",\n description=\"要分析的文本内容\", required=True)]\n\nprint(\"工具定义完成!共 9 个工具:\")\nprint(\" 检索类(6个): Semantic Scholar / AMiner / OpenAlex / PubMed / CrossRef / arXiv\")\nprint(\" 处理类(3个): CitationTool / PDFExtractTool / TextAnalysisTool\")" }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 第3部分:智能体构建\n", "\n", "本系统使用 **4 种智能体范式** 协同工作:\n", "\n", "| 智能体 | 范式 | 职责 |\n", "|--------|------|------|\n", "| SearchAgent | SimpleAgent | 文献检索与信息整理 |\n", "| SummaryAgent | SimpleAgent | 论文内容总结 |\n", "| PolishAgent | ReflectionAgent | 论文润色(自我反思迭代优化) |\n", "| OutlineAgent | PlanSolveAgent | 论文大纲结构化生成 |" ] }, { "cell_type": "code", "execution_count": null, "id": "1cd73c6c", "metadata": {}, "outputs": [], "source": "# 创建 LLM 实例(禁用 trace 日志以避免 Windows 编码问题)\nllm = HelloAgentsLLM()\nconfig = Config(trace_enabled=False)\n\n# 创建工具注册表,注册全部 9 个工具\ntool_registry = ToolRegistry()\ntool_registry.register_tool(LiteratureSearchTool()) # Semantic Scholar\ntool_registry.register_tool(AminerSearchTool()) # AMiner(中文论文)\ntool_registry.register_tool(OpenAlexSearchTool()) # OpenAlex\ntool_registry.register_tool(PubMedSearchTool()) # PubMed\ntool_registry.register_tool(CrossRefSearchTool()) # CrossRef\ntool_registry.register_tool(ArxivSearchTool()) # arXiv\ntool_registry.register_tool(CitationTool())\ntool_registry.register_tool(PDFExtractTool())\ntool_registry.register_tool(TextAnalysisTool())\n\n# ========================================\n# 智能体1: 文献检索助手 (SimpleAgent + 6 大检索工具)\n# ========================================\nsearch_system_prompt = \"\"\"你是一位学术文献检索专家。你有 6 个检索工具可用:\n\n- literature_search: Semantic Scholar,全学科覆盖(推荐首选)\n- aminer_search: AMiner,中文学术论文(中文文献首选)\n- openalex_search: OpenAlex,开放获取论文\n- pubmed_search: PubMed,生物医学领域\n- crossref_search: CrossRef,期刊论文元数据\n- arxiv_search: arXiv,CS/数学/物理预印本\n\n规则:\n1. 必须使用用户指定的检索工具获取真实数据\n2. 工具调用失败时直接报告错误,不要编造论文\n3. 基于真实结果进行分析和推荐\"\"\"\n\nsearch_agent = SimpleAgent(\n name=\"文献检索助手\", llm=llm,\n system_prompt=search_system_prompt, config=config\n)\nfor name in [\"literature_search\", \"aminer_search\", \"openalex_search\",\n \"pubmed_search\", \"crossref_search\", \"arxiv_search\"]:\n search_agent.add_tool(tool_registry.get_tool(name))\n\n# ========================================\n# 智能体2: 论文总结助手 (SimpleAgent)\n# ========================================\nsummary_system_prompt = \"\"\"你是一位学术论文审稿专家,擅长快速提取论文的核心信息。\n\n对于给定的论文内容,请按以下结构生成总结报告:\n\n## 论文信息\n- 标题、作者、发表年份、期刊/会议\n\n## 研究问题\n- 该论文要解决什么核心问题?\n\n## 方法与创新点\n- 采用了什么方法/模型/算法?\n- 相比已有工作,核心创新是什么?\n\n## 实验与结果\n- 在哪些数据集上做了实验?\n- 主要实验结果和性能指标\n\n## 贡献与局限\n- 论文的主要贡献(1-3点)\n- 论文的局限性或未解决的问题\n\n## 启发与延伸\n- 这篇论文对你的研究方向有什么启发?\n- 有哪些可以进一步探索的方向?\n\n请使用中文输出报告,专业术语保留英文。\"\"\"\n\nsummary_agent = SimpleAgent(\n name=\"论文总结助手\",\n llm=llm,\n system_prompt=summary_system_prompt,\n config=config\n)\n\n# ========================================\n# 智能体3: 论文润色助手 (SimpleAgent,多轮对话模式)\n# ========================================\n# 在 Web UI 中通过 create_polish_agent() 工厂函数创建独立实例\n# 每次新对话创建新 Agent,内部 history 自然累积上下文\n# 规则:保持原意、优化表达、记住上文修改历史\n\n# ========================================\n# 智能体4: 大纲生成助手 (SimpleAgent,多轮对话模式)\n# ========================================\n# 在 Web UI 中通过 create_outline_agent() 工厂函数创建独立实例\n# 每次新对话创建新 Agent,支持持续细化调整\n# 规则:结构化分解、支持\"细化第三章\"等后续指令\n\n# ========================================\n# 智能体5: 论文写作助手 (SimpleAgent + 6 大检索工具,多轮对话模式)\n# ========================================\n# 在 Web UI 中通过 create_paper_writer_agent() 工厂函数创建独立实例\n# 注册全部 6 个检索工具,确保引用真实文献\n# 规则:根据大纲逐章撰写、引用前必须先检索、杜绝编造文献\n# 支持\"写第二章\"、\"加入更多transformer相关讨论\"等后续指令\n\nprint(\"智能体创建完成!\")\nprint(\" 1. search_agent - 文献检索助手 (SimpleAgent + 6 检索工具)\")\nprint(\" 2. summary_agent - 论文总结助手 (SimpleAgent)\")\nprint(\" 3. polish_agent - 论文润色助手 (对话模式, Web UI)\")\nprint(\" 4. outline_agent - 大纲生成助手 (对话模式, Web UI)\")\nprint(\" 5. writer_agent - 论文写作助手 (对话模式 + 检索工具, Web UI)\")" }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 第4部分:功能演示\n", "\n", "### 📚 演示1:文献检索" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"=\" * 60)\n", "print(\"📚 演示1:文献检索\")\n", "print(\"=\" * 60)\n", "\n", "search_query = \"大语言模型在软件工程中的应用研究进展\"\n", "print(f\"\\n🔍 检索主题:{search_query}\\n\")\n", "\n", "search_result = search_agent.run(search_query)\n", "print(search_result)\n", "print(\"\\n\" + \"=\" * 60)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 📝 演示2:论文总结" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"=\" * 60)\n", "print(\"📝 演示2:论文总结\")\n", "print(\"=\" * 60)\n", "\n", "# 示例论文摘要\n", "sample_paper = \"\"\"\n", "论文标题: Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks\n", "作者: Patrick Lewis, Ethan Perez, Aleksandra Piktus, et al.\n", "发表: NeurIPS 2020\n", "\n", "摘要: Large pre-trained language models have been shown to store factual knowledge \n", "in their parameters, and achieve state-of-the-art results when fine-tuned on \n", "downstream NLP tasks. However, their ability to access and precisely manipulate \n", "knowledge is still limited, leading to factual errors and hallucinations. We \n", "introduce Retrieval-Augmented Generation (RAG), a general-purpose fine-tuning \n", "approach that combines pre-trained parametric and non-parametric memory for \n", "language generation. RAG models retrieve relevant documents from a dense vector \n", "index and condition the generation on both the input and retrieved documents. \n", "We evaluate RAG on a diverse set of NLP tasks including open-domain QA, abstractive \n", "question answering, and fact verification, achieving state-of-the-art results. \n", "Our analysis shows that RAG generates more specific, diverse, and factual language \n", "compared to parametric-only models.\n", "\"\"\"\n", "\n", "print(f\"\\n📄 待总结论文:{sample_paper[:80]}...\\n\")\n", "\n", "summary_result = summary_agent.run(\n", " f\"请对以下论文内容进行结构化总结:\\n\\n{sample_paper}\"\n", ")\n", "print(summary_result)\n", "print(\"\\n\" + \"=\" * 60)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 📎 演示3:引用生成" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"=\" * 60)\n", "print(\"📎 演示3:多格式引用生成\")\n", "print(\"=\" * 60)\n", "\n", "# 测试论文数据\n", "test_papers = [\n", " {\n", " \"title\": \"Attention Is All You Need\",\n", " \"authors\": \"Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., Polosukhin, I.\",\n", " \"journal\": \"Advances in Neural Information Processing Systems\",\n", " \"year\": \"2017\",\n", " \"volume\": \"30\",\n", " \"pages\": \"5998-6008\"\n", " },\n", " {\n", " \"title\": \"BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding\",\n", " \"authors\": \"Devlin, J., Chang, M. W., Lee, K., Toutanova, K.\",\n", " \"journal\": \"Proceedings of the 2019 Conference of the North American Chapter of the ACL\",\n", " \"year\": \"2019\",\n", " \"volume\": \"1\",\n", " \"pages\": \"4171-4186\"\n", " },\n", " {\n", " \"title\": \"Chain-of-Thought Prompting Elicits Reasoning in Large Language Models\",\n", " \"authors\": \"Wei, J., Wang, X., Schuurmans, D., Bosma, M., Ichter, B., Xia, F., Chi, E., Le, Q., Zhou, D.\",\n", " \"journal\": \"Advances in Neural Information Processing Systems\",\n", " \"year\": \"2022\",\n", " \"volume\": \"35\",\n", " \"pages\": \"24824-24837\"\n", " }\n", "]\n", "\n", "formats = [\"gbt7714\", \"apa\", \"mla\"]\n", "format_names = {\"gbt7714\": \"GB/T 7714 (中文标准)\", \"apa\": \"APA 7th\", \"mla\": \"MLA 9th\"}\n", "\n", "for i, paper in enumerate(test_papers, 1):\n", " print(f\"\\n--- 论文 {i}:{paper['title'][:50]}... ---\")\n", " for fmt in formats:\n", " paper[\"format\"] = fmt\n", " response = tool_registry.execute_tool(\"citation_generator\", json.dumps(paper))\n", " print(f\"\\n [{format_names[fmt]}]:\")\n", " print(f\" {response.text}\")\n", "\n", "print(\"\\n\" + \"=\" * 60)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ✍️ 演示4:论文润色" ] }, { "cell_type": "code", "execution_count": null, "id": "9a4a930a", "metadata": {}, "outputs": [], "source": [ "print(\"=\" * 60)\n", "print(\"✍️ 演示4:多轮对话式论文润色\")\n", "print(\"=\" * 60)\n", "\n", "# 模拟多轮对话\n", "round1 = \"\"\"请润色以下学术段落,使其更符合学术写作规范:\n", "\n", "In this paper, we propose a new method to solve the problem. Our method is very \n", "good and it works better than other methods. We did a lot of experiments.\"\"\"\n", "\n", "print(f\"\\n📝 【第1轮】用户: {round1[:80]}...\\n\")\n", "\n", "# 第一轮:初始润色\n", "polish_agent1 = SimpleAgent(\n", " name=\"润色\", llm=llm, config=config,\n", " system_prompt=\"你是学术论文语言编辑。润色后给出修改说明。\"\n", ")\n", "result1 = polish_agent1.run(f\"用户: {round1}\\n助手: \")\n", "print(result1[:500])\n", "print(\"\\n---\\n\")\n", "\n", "# 第二轮:基于上下文继续优化\n", "round2 = \"把第二句改得更学术化,使用更精确的词汇\"\n", "print(f\"📝 【第2轮】用户: {round2}\\n\")\n", "polish_agent2 = SimpleAgent(\n", " name=\"润色\", llm=llm, config=config,\n", " system_prompt=\"你是学术论文语言编辑。记住上下文,在已有基础上继续修改。\"\n", ")\n", "result2 = polish_agent2.run(\n", " f\"用户: {round1}\\n助手: {result1}\\n用户: {round2}\\n助手: \"\n", ")\n", "print(result2[:500])\n", "print(\"\\n\" + \"=\" * 60)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 📊 演示5:论文大纲生成" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"=\" * 60)\n", "print(\"📊 演示5:论文大纲生成(PlanSolveAgent)\")\n", "print(\"=\" * 60)\n", "\n", "outline_topic = \"基于大语言模型的多智能体协作系统的设计与实现\"\n", "print(f\"\\n📋 论文主题:{outline_topic}\\n\")\n", "print(\"🔄 PlanSolveAgent 正在拆解任务并生成大纲...\\n\")\n", "\n", "outline_result = outline_agent.run(\n", " f\"请为以下论文主题生成一份详细的结构化大纲:{outline_topic}\"\n", ")\n", "print(outline_result)\n", "print(\"\\n\" + \"=\" * 60)" ] }, { "cell_type": "markdown", "id": "74ef9eee", "source": "### 📝 演示6:论文写作(基于大纲 + 真实文献)\n\n展示如何根据大纲逐章撰写论文,写作过程中调用检索工具引用真实文献。", "metadata": {} }, { "cell_type": "code", "id": "85aba8fd", "source": "print(\"=\" * 60)\nprint(\"📝 演示6:论文写作(基于大纲 + 真实文献)\")\nprint(\"=\" * 60)\n\n# 模拟一个论文大纲\noutline = \"\"\"论文大纲:基于深度学习的医学影像分析综述\n第一章 引言\n第二章 医学影像与深度学习基础\n第三章 基于CNN的医学影像分析方法\n第四章 实验对比与性能评估\n第五章 未来展望与挑战\"\"\"\n\nprint(f\"\\n📋 给定大纲:\\n{outline}\\n\")\nprint(\"🔄 创建论文写作智能体(带文献检索能力)...\\n\")\n\n# 创建带检索工具的写作智能体\nwriter_llm = HelloAgentsLLM()\nwriter_agent = SimpleAgent(\n name=\"论文写作\", llm=writer_llm, config=config,\n system_prompt=\"\"\"你是学术论文写作专家。可以调用文献检索工具查找真实论文。\n引用文献时必须基于检索结果,绝对禁止编造论文。\"\"\"\n)\n# 注册检索工具,确保引用真实文献\nfor name in [\"literature_search\", \"aminer_search\"]:\n writer_agent.add_tool(tool_registry.get_tool(name))\n\n# 第一轮:写引言\nresult1 = writer_agent.run(\n f\"根据以下大纲,请撰写第一章引言部分(约300字)。\"\n f\"如果需要引用文献,请使用 literature_search 工具搜索真实论文:\\n{outline}\"\n)\nprint(\"--- 第一章 引言 ---\")\nprint(result1[:600])\nprint(\"...\\n\")\n\n# 第二轮:写方法部分,需要引用文献\nresult2 = writer_agent.run(\n \"请撰写第三章内容,介绍至少两种主流的基于CNN的医学影像分析方法。\"\n \"请使用 aminer_search 或 literature_search 工具搜索相关论文,并在正文中引用。\"\n)\nprint(\"--- 第三章 基于CNN的方法 ---\")\nprint(result2[:600])\nprint(\"...\\n\")\n\nprint(\"=\" * 60)", "metadata": {}, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 第5部分:文本分析工具演示" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"=\" * 60)\n", "print(\"📈 附加演示:文本统计分析\")\n", "print(\"=\" * 60)\n", "\n", "sample_text = \"\"\"\n", "大语言模型(Large Language Models, LLMs)在近年来取得了突破性进展。\n", "以GPT系列为代表的预训练语言模型在自然语言处理任务中展现出强大的能力。\n", "然而,LLMs在实际应用中仍面临幻觉问题、推理能力不足等挑战。\n", "本文综述了近年来关于LLM推理能力增强的研究进展,\n", "重点分析了Chain-of-Thought、Tree-of-Thought等提示方法的原理和效果。\n", "研究表明,结构化的推理路径设计能显著提升LLM在复杂推理任务上的表现。\n", "We systematically review recent advances in enhancing LLM reasoning capabilities.\n", "Our analysis covers both prompting-based methods and training-based approaches.\n", "The results demonstrate that structured reasoning significantly improves performance.\n", "\"\"\"\n", "\n", "response = tool_registry.execute_tool(\"text_analysis\", json.dumps({\"text\": sample_text}))\n", "print(response.text)\n", "print(\"\\n\" + \"=\" * 60)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 第6部分:总结与展望\n", "\n", "### ✅ 已实现的功能\n", "\n", "1. **文献检索** — 基于 SimpleAgent 的智能文献检索助手,提供系统化的检索策略\n", "2. **论文总结** — 结构化提取论文核心信息(问题、方法、贡献、局限)\n", "3. **引用生成** — 自定义 CitationTool 支持 GB/T 7714 / APA / MLA 三种格式\n", "4. **论文润色** — 基于 ReflectionAgent 的自我反思迭代优化\n", "5. **大纲生成** — 基于 PlanSolveAgent 的结构化论文大纲\n", "\n", "### 🔧 技术亮点\n", "\n", "- **多范式智能体协作**:融合了 SimpleAgent、ReflectionAgent、PlanSolveAgent 三种范式\n", "- **自定义工具系统**:基于 Tool + ToolParameter 实现了 CitationTool 和 TextAnalysisTool\n", "- **结构化输出**:每个功能都有清晰的 Markdown 格式输出\n", "\n", "### 🚧 遇到的挑战\n", "\n", "- LLM API 延迟波动,需通过 tool 端确定性计算弥补\n", "- 引用格式规则复杂,APA/MLA 的边缘情况需要进一步细化\n", "\n", "### 🔮 未来改进方向\n", "\n", "- [ ] 接入 arXiv API 实现实时论文检索\n", "- [ ] 支持 PDF 上传与解析\n", "- [ ] 增加论文查重分析功能\n", "- [ ] 构建 Gradio Web 界面\n", "- [ ] 引入多智能体辩论机制提升审稿质量" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.0" } }, "nbformat": 4, "nbformat_minor": 5 }