瀏覽代碼

Merge pull request #947 from Lemoween/feature/PaperAssistant

[毕业设计] PaperAssistant - 多智能体论文撰写助手
Sizhou Chen 1 月之前
父節點
當前提交
36f583c233
共有 22 個文件被更改,包括 2366 次插入 和 0 次删除
  1. 92 0
      Co-creation-projects/Lemoween-PaperAssistant/.env.example
  2. 413 0
      Co-creation-projects/Lemoween-PaperAssistant/README.md
  3. 288 0
      Co-creation-projects/Lemoween-PaperAssistant/agent.py
  4. 3 0
      Co-creation-projects/Lemoween-PaperAssistant/agents/__init__.py
  5. 375 0
      Co-creation-projects/Lemoween-PaperAssistant/agents/literature_search.py
  6. 98 0
      Co-creation-projects/Lemoween-PaperAssistant/config.py
  7. 97 0
      Co-creation-projects/Lemoween-PaperAssistant/main.py
  8. 48 0
      Co-creation-projects/Lemoween-PaperAssistant/models.py
  9. 155 0
      Co-creation-projects/Lemoween-PaperAssistant/prompts.py
  10. 42 0
      Co-creation-projects/Lemoween-PaperAssistant/requirements.txt
  11. 1 0
      Co-creation-projects/Lemoween-PaperAssistant/services/__init__.py
  12. 57 0
      Co-creation-projects/Lemoween-PaperAssistant/services/assembler.py
  13. 175 0
      Co-creation-projects/Lemoween-PaperAssistant/services/paper_library.py
  14. 90 0
      Co-creation-projects/Lemoween-PaperAssistant/services/planner.py
  15. 39 0
      Co-creation-projects/Lemoween-PaperAssistant/services/reviewer.py
  16. 70 0
      Co-creation-projects/Lemoween-PaperAssistant/services/tool_events.py
  17. 71 0
      Co-creation-projects/Lemoween-PaperAssistant/services/writer.py
  18. 10 0
      Co-creation-projects/Lemoween-PaperAssistant/tools/__init__.py
  19. 86 0
      Co-creation-projects/Lemoween-PaperAssistant/tools/citation_tool.py
  20. 46 0
      Co-creation-projects/Lemoween-PaperAssistant/tools/mcp_paper_search.py
  21. 82 0
      Co-creation-projects/Lemoween-PaperAssistant/tools/paper_library_tool.py
  22. 28 0
      Co-creation-projects/Lemoween-PaperAssistant/utils.py

+ 92 - 0
Co-creation-projects/Lemoween-PaperAssistant/.env.example

@@ -0,0 +1,92 @@
+# ============================================================
+# LLM 配置(由 HelloAgentsLLM 自动检测,参数优先,环境变量兜底)
+# ============================================================
+
+# --- 例 1:本地 Ollama ---
+LLM_PROVIDER=ollama
+LLM_BASE_URL=http://localhost:11434/v1
+LLM_API_KEY=ollama
+LLM_MODEL_ID=qwen2.5:7b
+
+# --- 例 2:DeepSeek 云端 ---
+# DEEPSEEK_API_KEY=sk-xxxxxxxxxxxx
+# LLM_MODEL_ID=deepseek-chat
+
+# --- 例 3:OpenAI ---
+# OPENAI_API_KEY=sk-xxxxxxxxxxxx
+# LLM_MODEL_ID=gpt-4o-mini
+
+# ============================================================
+# Qdrant 向量数据库(RAGTool + MemoryTool 使用)
+# ============================================================
+QDRANT_URL=http://localhost:6333
+QDRANT_API_KEY=
+QDRANT_COLLECTION=hello_agents_vectors
+QDRANT_VECTOR_SIZE=384
+QDRANT_DISTANCE=cosine
+QDRANT_TIMEOUT=30
+
+# ============================================================
+# Neo4j 图数据库(MemoryTool 的 semantic memory 使用)
+# ============================================================
+NEO4J_URI=bolt://localhost:7687
+NEO4J_USERNAME=neo4j
+NEO4J_PASSWORD=your_neo4j_password
+NEO4J_DATABASE=neo4j
+NEO4J_MAX_CONNECTION_LIFETIME=3600
+NEO4J_MAX_CONNECTION_POOL_SIZE=50
+NEO4J_CONNECTION_TIMEOUT=60
+
+# ============================================================
+# Embedding 服务(RAGTool 与 MemoryTool 的向量化后端)
+# 若 EMBED_API_KEY 留空,会自动回退到本地 sentence-transformers
+# ============================================================
+EMBED_MODEL_TYPE=dashscope
+EMBED_MODEL_NAME=text-embedding-v3
+EMBED_API_KEY=your_dashscope_api_key
+EMBED_BASE_URL=
+
+# ============================================================
+# Paper Search MCP(openags/paper-search-mcp)
+# 推荐:使用预装 venv 的 Python 解释器启动
+# ============================================================
+PAPER_SEARCH_MCP_COMMAND=.venv-paper-search\Scripts\python,-m,paper_search_mcp.server
+PAPER_SEARCH_MCP_PREFIX=papersearch
+
+# 备选:使用 uvx 直接运行(首次较慢,每次调用需重新解析依赖)
+# PAPER_SEARCH_MCP_COMMAND=uvx,--with,mcp<2,paper-search-mcp
+
+# 可选 API Key(提升速率与覆盖率,不配也能用)
+# PAPER_SEARCH_MCP_SEMANTIC_SCHOLAR_API_KEY=
+# PAPER_SEARCH_MCP_CORE_API_KEY=
+# PAPER_SEARCH_MCP_UNPAYWALL_EMAIL=you@example.com
+
+# ============================================================
+# 论文设置
+# ============================================================
+PAPER_TYPE=conference           # conference / journal / thesis
+CITATION_STYLE=gb7714           # gb7714 / apa
+TARGET_SECTIONS=5
+TARGET_WORDS_PER_SECTION=1000
+MAX_REFERENCES_PER_SECTION=5
+MAX_REVIEW_ROUNDS=2
+
+# ============================================================
+# 论文库
+# ============================================================
+PDF_DOWNLOAD_ENABLED=true
+MAX_PDF_SIZE_MB=50
+PAPER_LIBRARY_PATH=./workspace/paper_library
+
+# ============================================================
+# 笔记与记忆
+# ============================================================
+ENABLE_NOTES=true
+NOTES_WORKSPACE=./workspace/paper_notes
+ENABLE_MEMORY=true
+MEMORY_USER_ID=paper_author
+
+# ============================================================
+# 其他
+# ============================================================
+STRIP_THINKING_TOKENS=true

+ 413 - 0
Co-creation-projects/Lemoween-PaperAssistant/README.md

@@ -0,0 +1,413 @@
+# 论文撰写助手(PaperAssistant)
+
+基于 [HelloAgents](https://github.com/jjyaoao/HelloAgents) 框架构建的多智能体论文撰写助手。它能够根据给定的研究主题,自动完成**章节规划 → 文献检索 → PDF 下载 → RAG 索引 → 章节撰写 → 论文审校 → 最终汇总**的全流程,输出一份结构化的 Markdown 格式论文。
+
+
+
+------
+
+## 核心特性
+
+- **多智能体协作**:五个专职 Agent 分工完成规划、检索、撰写、审校、汇总
+- **学术来源限定**:所有文献来自 arXiv、Semantic Scholar、CrossRef、OpenAlex 等学术数据库,杜绝网页链接
+- **真实文献支撑**:通过 [Paper Search MCP](https://github.com/openags/paper-search-mcp) 下载论文全文,经 RAG 索引供撰写时调用
+- **检索增强生成(RAG)**:论文库基于 Qdrant 向量库构建,支持语义检索、MQE 多查询扩展与 HyDE 假设文档嵌入
+- **结构化笔记**:使用 HelloAgents 的 `NoteTool` 保存章节草稿、大纲与终稿,支持跨会话恢复
+- **多层次记忆**:使用 `MemoryTool` 管理工作记忆、情景记忆与语义记忆
+- **工具调用追踪**:所有工具调用通过 `ToolCallTracker` 记录,便于调试与审计
+- **引用格式规范**:支持 GB/T 7714引用风格
+
+------
+
+## 系统架构
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│                      用户:输入研究主题                       │
+└─────────────────────────────┬───────────────────────────────┘
+                              │
+                    ┌─────────▼──────────┐
+                    │  PaperAssistant    │ 协调器
+                    │  (Orchestrator)    │
+                    └─────────┬──────────┘
+                              │
+       ┌──────────────────────┼──────────────────────┐
+       │                      │                      │
+  ┌────▼─────┐          ┌─────▼────┐          ┌─────▼────┐
+  │ Planner  │   →      │ Searcher │   →      │  Writer  │
+  │ 章节规划  │          │ 文献检索  │          │ 章节撰写  │
+  └──────────┘          └─────┬────┘          └─────┬────┘
+                              │                      │
+                              │ 下载 PDF              │ 检索论文原文
+                              │                      │
+                     ┌────────▼──────┐      ┌────────▼─────┐
+                     │ PaperLibrary  │◄─────│ search_paper │
+                     │  (RAGTool)    │      │   _library   │
+                     └────────┬──────┘      └──────────────┘
+                              │
+                  ┌───────────▼───────────┐
+                  │  Reviewer → Assembler │
+                  │  审校    →  汇总成稿   │
+                  └───────────────────────┘
+```
+
+
+
+**五个专职 Agent**:
+
+| Agent                 | 职责                                  | 工具                                                    |
+| :-------------------- | :------------------------------------ | :------------------------------------------------------ |
+| PaperPlannerAgent     | 将研究主题拆解为 3-5 个章节           | `NoteTool`                                              |
+| LiteratureSearchAgent | 检索学术论文、下载 PDF、加入 RAG 索引 | `Paper Search MCP` + `RAGTool`                          |
+| SectionWriterAgent    | 撰写章节正文,引用文献                | `search_paper_library` + `format_citation` + `NoteTool` |
+| PaperReviewAgent      | 审校论文的逻辑、引用、术语一致性      | `NoteTool`                                              |
+| ReportAssemblerAgent  | 汇总章节生成最终论文                  | `NoteTool`                                              |
+
+------
+
+## 环境要求
+
+| 组件                          | 版本   | 用途                                 |
+| :---------------------------- | :----- | :----------------------------------- |
+| Python                        | ≥ 3.10 | 运行环境                             |
+| uv                            | ≥ 0.4  | 管理 Paper Search MCP 依赖           |
+| Ollama 或其他 OpenAI 兼容 LLM | 任意   | 提供 LLM 能力                        |
+| Qdrant                        | ≥ 1.7  | RAG 向量存储(本地 Docker 或云服务) |
+| Neo4j                         | ≥ 5.x  | 语义记忆图存储(可选,可禁用)       |
+
+
+
+------
+
+## 安装步骤
+
+### 1. 安装 Python 依赖
+
+```
+# 推荐使用虚拟环境
+python -m venv .venv
+# Windows
+.venv\Scripts\activate
+# Linux/macOS
+source .venv/bin/activate
+
+# 安装依赖
+pip install -r requirements.txt
+```
+
+
+
+### 2. 安装 uv(用于运行 Paper Search MCP)
+
+
+
+```
+# Windows PowerShell
+powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
+```
+
+
+
+```
+# Linux / macOS
+curl -LsSf https://astral.sh/uv/install.sh | sh
+```
+
+
+
+### 3. 安装 spaCy 语言模型
+
+
+
+```
+python -m spacy download zh_core_web_sm
+python -m spacy download en_core_web_sm
+```
+
+
+
+### 4. 预装 Paper Search MCP(强烈推荐)
+
+为了避免每次调用都重新解析依赖,强烈建议**预装到专属 venv**:
+
+```
+# 在项目根目录
+uv venv .venv-paper-search
+
+# Windows
+uv pip install --python .venv-paper-search `
+  -i https://pypi.tuna.tsinghua.edu.cn/simple `
+  "mcp<2" paper-search-mcp
+
+# Linux/macOS
+uv pip install --python .venv-paper-search \
+  -i https://pypi.tuna.tsinghua.edu.cn/simple \
+  "mcp<2" paper-search-mcp
+```
+
+**注意**:`paper-search-mcp` 目前依赖 `mcp<2`,必须显式 pin 版本,否则会因 `mcp 2.x` 中 `fastmcp` 重命名而启动失败。
+
+------
+
+## 配置说明
+
+在项目根目录创建 `.env` 文件:
+
+```
+cp .env.example .env
+```
+
+
+
+### 完整 `.env` 示例
+
+```
+# ============================================================
+# LLM 配置(由 HelloAgentsLLM 自动检测,参数优先,环境变量兜底)
+# ============================================================
+
+# --- 例 1:本地 Ollama ---
+LLM_PROVIDER=ollama
+LLM_BASE_URL=http://localhost:11434/v1
+LLM_API_KEY=ollama
+LLM_MODEL_ID=qwen2.5:7b
+
+# --- 例 2:DeepSeek 云端 ---
+# DEEPSEEK_API_KEY=sk-xxxxxxxxxxxx
+# LLM_MODEL_ID=deepseek-chat
+
+# --- 例 3:OpenAI ---
+# OPENAI_API_KEY=sk-xxxxxxxxxxxx
+# LLM_MODEL_ID=gpt-4o-mini
+
+# ============================================================
+# Qdrant 向量数据库(RAGTool + MemoryTool 使用)
+# ============================================================
+QDRANT_URL=http://localhost:6333
+QDRANT_API_KEY=
+QDRANT_COLLECTION=hello_agents_vectors
+QDRANT_VECTOR_SIZE=384
+QDRANT_DISTANCE=cosine
+QDRANT_TIMEOUT=30
+
+# ============================================================
+# Neo4j 图数据库(MemoryTool 的 semantic memory 使用)
+# ============================================================
+NEO4J_URI=bolt://localhost:7687
+NEO4J_USERNAME=neo4j
+NEO4J_PASSWORD=your_neo4j_password
+NEO4J_DATABASE=neo4j
+NEO4J_MAX_CONNECTION_LIFETIME=3600
+NEO4J_MAX_CONNECTION_POOL_SIZE=50
+NEO4J_CONNECTION_TIMEOUT=60
+
+# ============================================================
+# Embedding 服务(RAGTool 与 MemoryTool 的向量化后端)
+# 若 EMBED_API_KEY 留空,会自动回退到本地 sentence-transformers
+# ============================================================
+EMBED_MODEL_TYPE=dashscope
+EMBED_MODEL_NAME=text-embedding-v3
+EMBED_API_KEY=your_dashscope_api_key
+EMBED_BASE_URL=
+
+# ============================================================
+# Paper Search MCP(openags/paper-search-mcp)
+# 推荐:使用预装 venv 的 Python 解释器启动
+# ============================================================
+PAPER_SEARCH_MCP_COMMAND=.venv-paper-search\Scripts\python,-m,paper_search_mcp.server
+PAPER_SEARCH_MCP_PREFIX=papersearch
+
+# 备选:使用 uvx 直接运行(首次较慢,每次调用需重新解析依赖)
+# PAPER_SEARCH_MCP_COMMAND=uvx,--with,mcp<2,paper-search-mcp
+
+# 可选 API Key(提升速率与覆盖率,不配也能用)
+# PAPER_SEARCH_MCP_SEMANTIC_SCHOLAR_API_KEY=
+# PAPER_SEARCH_MCP_CORE_API_KEY=
+# PAPER_SEARCH_MCP_UNPAYWALL_EMAIL=you@example.com
+
+# ============================================================
+# 论文设置
+# ============================================================
+PAPER_TYPE=conference           # conference / journal / thesis
+CITATION_STYLE=gb7714           # gb7714 / apa
+TARGET_SECTIONS=5
+TARGET_WORDS_PER_SECTION=1000
+MAX_REFERENCES_PER_SECTION=5
+MAX_REVIEW_ROUNDS=2
+
+# ============================================================
+# 论文库
+# ============================================================
+PDF_DOWNLOAD_ENABLED=true
+MAX_PDF_SIZE_MB=50
+PAPER_LIBRARY_PATH=./workspace/paper_library
+
+# ============================================================
+# 笔记与记忆
+# ============================================================
+ENABLE_NOTES=true
+NOTES_WORKSPACE=./workspace/paper_notes
+ENABLE_MEMORY=true
+MEMORY_USER_ID=paper_author
+
+# ============================================================
+# 其他
+# ============================================================
+STRIP_THINKING_TOKENS=true
+```
+
+
+
+### 配置说明
+
+| 变量                         | 含义                                             |
+| :--------------------------- | :----------------------------------------------- |
+| `LLM_*` / `*_API_KEY`        | LLM 连接信息,由 `HelloAgentsLLM` 自动检测       |
+| `QDRANT_URL`                 | Qdrant 向量库地址,RAG 索引与记忆系统的核心依赖  |
+| `NEO4J_*`                    | Neo4j 图数据库,只有启用 `semantic` 记忆时才需要 |
+| `EMBED_*`                    | 文本嵌入服务,留空则回退本地模型                 |
+| `PAPER_SEARCH_MCP_COMMAND`   | MCP 服务器启动命令,逗号分隔                     |
+| `TARGET_SECTIONS`            | 论文目标章节数                                   |
+| `MAX_REFERENCES_PER_SECTION` | 每章最多检索的论文数                             |
+| `PAPER_LIBRARY_PATH`         | 论文库路径,存放 PDF 与 RAG 索引                 |
+
+------
+
+## 使用方法
+
+### 基本用法
+
+```
+python main.py "大语言模型在学术写作辅助中的应用与挑战"
+```
+
+
+
+### 快速测试(减少耗时)
+
+在 `.env` 中临时调整:
+
+```
+TARGET_SECTIONS=3
+TARGET_WORDS_PER_SECTION=200
+MAX_REFERENCES_PER_SECTION=3
+```
+
+
+
+然后运行:
+
+```
+python main.py "大语言模型在学术写作辅助中的应用与挑战"
+```
+
+
+
+### 使用自定义主题
+
+```
+python main.py "联邦学习在医疗影像中的应用"
+python main.py "量子机器学习的最新进展"
+```
+
+
+
+------
+
+## 输出产物
+
+运行完成后,产物位于 `workspace/` 目录下:
+
+```
+workspace/
+├── output/
+│   ├── paper_<主题>.md              # 最终论文(Markdown)
+│   └── review_<主题>.md             # 审校意见
+├── paper_notes/                     # NoteTool 工作区
+│   ├── note_xxx_0.md                # 章节 1 笔记(task_state)
+│   ├── note_xxx_1.md                # 章节 2 笔记
+│   └── note_xxx_N.md                # 论文终稿(conclusion)
+├── paper_memory/                    # MemoryTool 数据
+│   └── memory.db
+└── paper_library/                   # RAGTool 论文库
+    ├── pdfs/                        # 下载的论文 PDF
+    │   ├── 2502.00632v2.pdf
+    │   ├── 2404.00027v5.pdf
+    │   └── ...
+    └── rag/
+        └── index_manifest.json      # 索引清单
+```
+
+
+
+### 论文输出格式
+
+最终论文为 Markdown 格式,包含:
+
+- **标题**:由规划 Agent 生成
+- **摘要**:200-300 字,概括研究背景、方法、主要发现
+- **正文**:引言、相关工作、方法、实验/分析、结论等章节
+- **参考文献**:统一格式,DOI 可追溯
+
+------
+
+## 项目结构
+
+```
+PaperAssistant/
+├── README.md                          # 本文档
+├── requirements.txt                   # Python 依赖
+├── .env.example                       # 环境变量模板
+├── main.py                            # 入口脚本
+├── config.py                          # 应用层配置
+├── models.py                          # 数据模型
+├── prompts.py                         # 提示词模板
+├── utils.py                           # 通用工具函数
+├── agent.py                           # 协调器
+│
+├── tools/                             # 工具层
+│   ├── __init__.py
+│   ├── citation_tool.py               # 引用格式化
+│   ├── paper_library_tool.py          # 论文库检索/问答
+│   └── mcp_paper_search.py            # Paper Search MCP 工厂
+│
+├── services/                          # 服务层
+│   ├── __init__.py
+│   ├── paper_library.py               # 论文库服务(包装 RAGTool)
+│   ├── planner.py                     # 章节规划服务
+│   ├── writer.py                      # 章节撰写服务
+│   ├── reviewer.py                    # 论文审校服务
+│   ├── assembler.py                   # 论文汇总服务
+│   └── tool_events.py                 # 工具调用追踪
+│
+└── agents/                            # Agent 层
+    ├── __init__.py
+    └── literature_search.py           # 文献检索 Agent
+```
+
+
+
+
+
+------
+
+## 许可证
+
+本项目采用 MIT License 授权。
+
+
+
+------
+
+## 作者
+
+- **GitHub**:[@Lemoween](https://github.com/Lemoween)
+- **Email**:lemoween@163.com
+
+
+
+------
+
+## 致谢
+
+感谢Datawhale社区和Hello-Agents项目!

+ 288 - 0
Co-creation-projects/Lemoween-PaperAssistant/agent.py

@@ -0,0 +1,288 @@
+"""论文撰写助手协调器
+
+五个专职 Agent:
+  - PaperPlannerAgent      章节规划
+  - LiteratureSearchAgent  学术检索 + PDF 下载 + RAG 索引
+  - SectionWriterAgent     章节撰写(检索论文原文)
+  - PaperReviewAgent       论文审校
+  - ReportAssemblerAgent   最终论文汇总
+
+"""
+from __future__ import annotations
+
+import logging
+import re
+from pathlib import Path
+from typing import Any, Optional
+
+from hello_agents import HelloAgentsLLM, ToolAwareSimpleAgent
+from hello_agents.tools import MemoryTool, NoteTool, ToolRegistry
+
+from agents.literature_search import LiteratureSearchAgent
+from config import Configuration
+from models import PaperState, PaperStateOutput
+from prompts import (
+    paper_planner_system_prompt,
+    paper_reviewer_system_prompt,
+    report_assembler_system_prompt,
+    section_writer_system_prompt,
+)
+from services.assembler import ReportAssemblyService
+from services.planner import PlanningService
+from services.reviewer import ReviewService
+from services.tool_events import ToolCallTracker
+from services.writer import SectionWritingService
+from tools import PaperLibraryAskTool, PaperLibrarySearchTool
+
+logger = logging.getLogger(__name__)
+
+
+class PaperAssistantAgent:
+    """论文撰写助手协调器"""
+
+    def __init__(self, config: Optional[Configuration] = None) -> None:
+        self.config = config or Configuration.from_env()
+        self.llm = self._init_llm()
+
+        # ---------- 内置工具 ----------
+        self.note_tool = (
+            NoteTool(workspace=self.config.notes_workspace)
+            if self.config.enable_notes else None
+        )
+        self.memory_tool = (
+            MemoryTool(user_id=self.config.memory_user_id)
+            if self.config.enable_memory else None
+        )
+
+        # ---------- 工具调用追踪 ----------
+        self._tool_tracker = ToolCallTracker(
+            notes_workspace=self.config.notes_workspace
+            if self.config.enable_notes else None
+        )
+
+        # ---------- 五个专职 Agent ----------
+        self.planner_agent = self._make_agent(
+            "论文规划专家", paper_planner_system_prompt.strip()
+        )
+        self.writer_agent = self._make_agent(
+            "章节撰写专家", section_writer_system_prompt.strip()
+        )
+        self.reviewer_agent = self._make_agent(
+            "论文审校专家", paper_reviewer_system_prompt.strip()
+        )
+        self.assembler_agent = self._make_agent(
+            "报告汇总专家", report_assembler_system_prompt.strip()
+        )
+
+        # ---------- 文献检索 Agent ----------
+        self.search_agent = LiteratureSearchAgent(
+            llm=self.llm,
+            config=self.config,
+            tool_tracker=self._tool_tracker,
+        )
+
+        # ---------- 为写作 Agent 装配论文库检索工具(通过 add_tool) ----------
+        self.writer_agent.add_tool(
+            PaperLibrarySearchTool(self.search_agent.library)
+        )
+        self.writer_agent.add_tool(
+            PaperLibraryAskTool(self.search_agent.library)
+        )
+
+        # ---------- 服务封装 ----------
+        self.planner = PlanningService(self.planner_agent, self.config)
+        self.writer = SectionWritingService(
+            lambda: self.writer_agent, self.config
+        )
+        self.reviewer = ReviewService(
+            lambda: self.reviewer_agent, self.config
+        )
+        self.assembler = ReportAssemblyService(
+            lambda: self.assembler_agent, self.config
+        )
+
+    # ------------------------------------------------------------------
+    def _init_llm(self) -> HelloAgentsLLM:
+        """初始化 LLM 客户端
+
+        直接交给 HelloAgentsLLM 的自动检测机制处理:
+        - 参数优先,环境变量兜底;
+        - 读取 LLM_PROVIDER / LLM_API_KEY / LLM_BASE_URL / LLM_MODEL_ID,
+          或 OPENAI_API_KEY / DEEPSEEK_API_KEY / DASHSCOPE_API_KEY 等;
+        - 根据 base_url 或 api_key 格式自动识别 provider。
+
+        应用层不感知 provider 细节,只设置业务相关参数(temperature=0.0)。
+        """
+        return HelloAgentsLLM(temperature=0.0)
+
+    def _make_agent(self, name: str, system_prompt: str) -> ToolAwareSimpleAgent:
+        """为每个 Agent 装配 NoteTool + MemoryTool(共享 registry)"""
+        registry = ToolRegistry()
+        if self.note_tool:
+            registry.register_tool(self.note_tool)
+        if self.memory_tool:
+            registry.register_tool(self.memory_tool)
+
+        return ToolAwareSimpleAgent(
+            name=name,
+            llm=self.llm,
+            system_prompt=system_prompt,
+            enable_tool_calling=True,
+            tool_registry=registry,
+            tool_call_listener=self._tool_tracker.record,
+        )
+
+    # ------------------------------------------------------------------
+    def run(self, topic: str) -> PaperStateOutput:
+        """执行完整论文撰写流程"""
+        state = PaperState(
+            research_topic=topic,
+            paper_type=self._enum_value(self.config.paper_type),
+            citation_style=self._enum_value(self.config.citation_style),
+        )
+
+        # 1) 记录研究主题到情景记忆
+        if self.memory_tool:
+            self.memory_tool.run({
+                "action": "add",
+                "content": f"开始撰写论文,研究主题:{topic}",
+                "memory_type": "episodic",
+                "importance": 0.9,
+            })
+
+        # 2) 章节规划
+        logger.info("→ 规划章节大纲")
+        sections = self.planner.plan_outline(state)
+        if not sections:
+            sections = PlanningService.create_fallback_sections()
+        state.sections = sections
+        self._drain_events()
+
+        # 3) 逐章检索 + 撰写
+        previous_context = ""
+        for section in sections:
+            logger.info("→ 章节 %d: %s", section.id, section.title)
+
+            # 3.1 学术检索 + PDF 下载 + RAG 索引
+            refs = self.search_agent.search_for_section(section)
+            section.references = refs
+            logger.info("   检索到 %d 篇,其中 %d 篇已下载索引",
+                        len(refs), sum(1 for r in refs if r.get("indexed")))
+
+            # 3.2 撰写章节(Writer Agent 可调用 search_paper_library 检索原文)
+            content = self.writer.write_section(
+                state, section, refs, previous_context
+            )
+            section.content = content
+            section.status = "completed"
+            previous_context += f"\n\n## {section.title}\n{content[:500]}"
+
+            # 3.3 保存章节笔记(NoteTool)
+            if self.note_tool:
+                note_body = (
+                    f"## 章节意图\n{section.intent}\n\n"
+                    f"## 关键词\n{', '.join(section.keywords)}\n\n"
+                    f"## 章节正文(节选)\n{content[:1500]}\n\n"
+                    f"## 参考文献\n"
+                    + "\n".join(
+                        f"- {r.get('title', '')} "
+                        f"{'[已索引]' if r.get('indexed') else ''}"
+                        for r in refs
+                    )
+                )
+                resp = self.note_tool.run({
+                    "action": "create",
+                    "title": f"章节 {section.id}: {section.title}",
+                    "note_type": "conclusion",
+                    "tags": ["paper", f"section_{section.id}"],
+                    "content": note_body,
+                })
+                m = re.search(r"ID:\s*([^\n]+)", resp or "")
+                if m:
+                    section.note_id = m.group(1).strip()
+                    if self.config.notes_workspace:
+                        section.note_path = str(
+                            Path(self.config.notes_workspace)
+                            / f"{section.note_id}.md"
+                        )
+
+            self._drain_events()
+
+            # 3.4 记录撰写事件到情景记忆
+            if self.memory_tool:
+                self.memory_tool.run({
+                    "action": "add",
+                    "content": f"完成章节「{section.title}」撰写",
+                    "memory_type": "episodic",
+                    "importance": 0.7,
+                })
+
+        # 4) 审校
+        logger.info("→ 审校论文")
+        full_draft = self._assemble_draft(state, sections)
+        review_notes = self.reviewer.review(state, full_draft)
+        state.review_notes = review_notes
+        self._drain_events()
+
+        # 5) 汇总
+        logger.info("→ 汇总最终论文")
+        final_paper = self.assembler.assemble(state, sections, review_notes)
+        state.final_paper = final_paper
+        self._drain_events()
+
+        # 6) 保存终稿到笔记(NoteTool)
+        if self.note_tool and final_paper:
+            resp = self.note_tool.run({
+                "action": "create",
+                "title": f"论文终稿:{state.paper_title or topic}",
+                "note_type": "conclusion",
+                "tags": ["paper", "final"],
+                "content": final_paper[:5000],
+            })
+            m = re.search(r"ID:\s*([^\n]+)", resp or "")
+            if m:
+                state.report_note_id = m.group(1).strip()
+                if self.config.notes_workspace:
+                    state.report_note_path = str(
+                        Path(self.config.notes_workspace)
+                        / f"{state.report_note_id}.md"
+                    )
+
+        # 7) 记录完成事件
+        if self.memory_tool:
+            total_refs = sum(len(s.references) for s in sections)
+            indexed_refs = sum(
+                1 for s in sections for r in s.references if r.get("indexed")
+            )
+            self.memory_tool.run({
+                "action": "add",
+                "content": (
+                    f"论文《{state.paper_title or topic}》完成,"
+                    f"共 {len(sections)} 章,"
+                    f"{total_refs} 篇参考文献({indexed_refs} 篇已索引)"
+                ),
+                "memory_type": "episodic",
+                "importance": 0.9,
+            })
+
+        return PaperStateOutput(
+            paper_markdown=final_paper,
+            sections=sections,
+            references=[r for s in sections for r in s.references],
+            review_notes=review_notes,
+            library_stats=self.search_agent.library_stats(),
+        )
+
+    # ------------------------------------------------------------------
+    def _assemble_draft(self, state: PaperState, sections) -> str:
+        parts = [f"# {state.paper_title or state.research_topic}\n"]
+        for s in sections:
+            parts.append(f"## {s.title}\n\n{s.content or ''}\n")
+        return "\n".join(parts)
+
+    def _drain_events(self) -> list[dict[str, Any]]:
+        return self._tool_tracker.drain()
+
+    @staticmethod
+    def _enum_value(v: Any) -> str:
+        return v.value if hasattr(v, "value") else str(v)

+ 3 - 0
Co-creation-projects/Lemoween-PaperAssistant/agents/__init__.py

@@ -0,0 +1,3 @@
+from .literature_search import LiteratureSearchAgent
+
+__all__ = ["LiteratureSearchAgent"]

+ 375 - 0
Co-creation-projects/Lemoween-PaperAssistant/agents/literature_search.py

@@ -0,0 +1,375 @@
+"""文献检索 Agent(基于 Paper Search MCP)
+
+链路:
+  LLM 调用 papersearch_search_papers → 返回 JSON(含 source + paper_id)
+  Python 层逐篇调用 MCPTool.run({action: call_tool, ...}) → 直接调用 download_with_fallback
+  下载成功的 PDF → PaperLibraryService.index_paper(内部走 RAGTool)
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import re
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from hello_agents import HelloAgentsLLM, ToolAwareSimpleAgent
+
+from config import Configuration
+from models import PaperSection
+from prompts import literature_search_system_prompt
+from services.paper_library import PaperLibraryService
+from services.tool_events import ToolCallTracker
+from tools import create_paper_search_mcp_tool
+
+logger = logging.getLogger(__name__)
+
+
+class LiteratureSearchAgent:
+    """文献检索 Agent:检索 → 下载 → RAG 索引"""
+
+    def __init__(
+        self,
+        llm: HelloAgentsLLM,
+        config: Configuration,
+        tool_tracker: Optional[ToolCallTracker] = None,
+    ):
+        self._config = config
+        self._tracker = tool_tracker
+        self._prefix = config.paper_search_mcp_prefix
+        self._mcp_tool = None  # ★ 保存原始 MCPTool 引用
+
+        # 1. 论文库服务(复用第八章 RAGTool)
+        self.library = PaperLibraryService(
+            library_path=config.paper_library_path,
+            rag_namespace=config.paper_library_rag_namespace,
+            pdf_dir=str(config.paper_library_path.rstrip("/") + "/pdfs"),
+        )
+
+        # 2. Agent(参照第十四章 ToolAwareSimpleAgent 用法)
+        self._agent = ToolAwareSimpleAgent(
+            name="文献检索专家",
+            llm=llm,
+            system_prompt="你是一名学术文献检索专家。",
+            enable_tool_calling=True,
+            tool_registry=None,
+            tool_call_listener=self._tracker.record if self._tracker else None,
+        )
+
+        # 3. 装配 Paper Search MCP
+        self._register_mcp_tool()
+
+        # 4. 刷新系统提示
+        self._agent.system_prompt = self._build_system_prompt()
+
+    # ------------------------------------------------------------------
+    def _register_mcp_tool(self) -> None:
+        """装配 Paper Search MCP"""
+        command = self._config.resolve_paper_search_mcp_command()
+        if not command:
+            logger.warning("未配置 PAPER_SEARCH_MCP_COMMAND,文献检索能力不可用")
+            return
+
+        try:
+            mcp_tool = create_paper_search_mcp_tool(
+                server_command=command,
+                prefix=self._prefix,
+            )
+            self._agent.add_tool(mcp_tool)
+            self._mcp_tool = mcp_tool     # ★ 保存引用,供直接调用
+            logger.info("Paper Search MCP 已装配: %s", command)
+        except Exception as exc:
+            logger.exception("Paper Search MCP 装配失败: %s", exc)
+
+    def _build_system_prompt(self) -> str:
+        """★ 补回此方法:把工具清单注入检索提示词"""
+        tools_desc = (
+            self._agent.tool_registry.get_tools_description()
+            if self._agent.tool_registry else "暂无可用工具"
+        )
+        return literature_search_system_prompt.format(
+            tools_placeholder=tools_desc,
+            prefix=self._prefix,
+        )
+
+    # ------------------------------------------------------------------
+    def search_for_section(self, section: PaperSection) -> List[Dict[str, Any]]:
+        """对单个章节执行检索 → 下载 → 索引"""
+        keywords = section.keywords or [section.title]
+        query = " ".join(keywords)
+        limit = self._config.max_references_per_section
+
+        # ------ 步骤 1: 让 LLM 调用 papersearch_search_papers 完成检索 ------
+        prompt = (
+            f"请为以下论文章节检索 {limit} 篇高质量学术论文。\n\n"
+            f"章节标题:{section.title}\n"
+            f"章节意图:{section.intent}\n"
+            f"检索关键词:{query}\n\n"
+            f"## 操作指令\n"
+            f"调用一次 `{self._prefix}_search_papers`,参数:\n"
+            f"```json\n"
+            f'{{"query": "{query}", '
+            f'"sources": "arxiv,semantic,crossref,openalex,dblp", '
+            f'"max_results_per_source": {limit}}}\n'
+            f"```\n\n"
+            f"## 返回要求\n"
+            f"检索完成后,**只输出 JSON**,格式如下(不要任何解释文字):\n"
+            f'{{"papers": ['
+            f'{{"title":"...","authors":[...],"year":...,'
+            f'"venue":"...","doi":"...","source":"arxiv",'
+            f'"paper_id":"..."}}]}}\n'
+            f"注意:source 与 paper_id 必填,用于后续下载。"
+        )
+
+        response = self._agent.run(prompt)
+
+        # ===== 诊断 1:检索 Agent 原始输出 =====
+        print("=" * 70)
+        print("【诊断】检索 Agent 原始输出:")
+        print(response[:2000])
+        print("=" * 70)
+
+        papers = self._parse_papers(response)
+        papers = self._deduplicate(papers)[:limit]
+
+        # ===== 诊断 2:解析出的 papers 列表 =====
+        print("=" * 70)
+        print(f"【诊断】解析出 {len(papers)} 篇论文:")
+        for i, p in enumerate(papers, 1):
+            print(f"  [{i}] title     : {(p.get('title') or '')[:60]}")
+            print(f"      source    : {p.get('source')!r}")
+            print(f"      paper_id  : {p.get('paper_id')!r}")
+            print(f"      arxiv_id  : {p.get('arxiv_id')!r}")
+            print(f"      doi       : {p.get('doi')!r}")
+            print(f"      所有字段  : {list(p.keys())}")
+        print("=" * 70)
+
+        # ------ 步骤 2: Python 层逐篇调用 download_with_fallback ------
+        for p in papers:
+            self._download_paper(p)
+
+        # ------ 步骤 3: 已下载的 PDF 加入 RAG 索引 ------
+        for p in papers:
+            self._index_if_downloaded(p)
+
+        logger.info(
+            "章节「%s」检索 %d 篇,已下载 %d 篇,已索引 %d 篇",
+            section.title, len(papers),
+            sum(1 for p in papers if p.get("pdf_path")),
+            sum(1 for p in papers if p.get("indexed")),
+        )
+        return papers
+
+    # ------------------------------------------------------------------
+    def _download_paper(self, paper: Dict[str, Any]) -> None:
+        """调用 download_with_fallback 下载单篇论文
+
+        直接调用底层 MCPTool.run(),避免经过 wrapper 的参数包装。
+        """
+        source = (paper.get("source") or "").strip()
+        paper_id = (paper.get("paper_id") or "").strip()
+        if not source or not paper_id:
+            logger.debug("论文《%s》缺少 source/paper_id,跳过下载",
+                         (paper.get("title") or "")[:60])
+            paper["pdf_path"] = None
+            return
+
+        unsupported = {"google_scholar", "dblp", "ssrn", "unpaywall"}
+        if source in unsupported:
+            logger.debug("源 %s 不支持全文下载,跳过", source)
+            paper["pdf_path"] = None
+            return
+
+        if self._mcp_tool is None:
+            logger.warning("MCPTool 未装配,无法下载")
+            paper["pdf_path"] = None
+            return
+
+        save_path = str(self.library.pdf_dir)
+
+        # ===== 诊断 =====
+        print("=" * 70)
+        print("【诊断】直接调用 MCPTool.run() 下载:")
+        print(f"  source   : {source!r}")
+        print(f"  paper_id : {paper_id!r}")
+        print(f"  save_path: {save_path!r}")
+        print("=" * 70)
+
+        # ★ 关键:直接调用 MCPTool,参数不经过 wrapper 的 {"input": ...} 包装
+        try:
+            result = self._mcp_tool.run({
+                "action": "call_tool",
+                "tool_name": "download_with_fallback",
+                "arguments": {
+                    "source": source,
+                    "paper_id": paper_id,
+                    "doi": paper.get("doi", "") or "",
+                    "title": paper.get("title", "") or "",
+                    "save_path": save_path,
+                    "use_scihub": False,
+                },
+            })
+        except Exception as exc:
+            logger.warning("下载工具调用失败 source=%s paper_id=%s: %s",
+                           source, paper_id, exc)
+            paper["pdf_path"] = None
+            return
+
+        # ===== 诊断 =====
+        print("=" * 70)
+        print("【诊断】download_with_fallback 返回值(全文):")
+        print(str(result))
+        print("=" * 70)
+
+        pdf_path = self._extract_pdf_path(str(result))
+        paper["pdf_path"] = pdf_path
+        if pdf_path:
+            logger.info("下载成功: %s", pdf_path)
+        else:
+            logger.debug("未能从下载结果中提取 PDF 路径: %s", str(result)[:200])
+
+    @staticmethod
+    def _extract_pdf_path(result_text: str) -> Optional[str]:
+        """从 download_with_fallback 的返回值里提取 PDF 路径
+
+        典型返回值:
+            工具 'download_with_fallback' 执行结果:
+            workspace\\paper_library\\pdfs/2502.00632v2.pdf
+
+        提取规则:
+        1. 逐行从后往前找以 .pdf 结尾的行,去掉 "xxx:" 前缀
+        2. 若整行就是路径,直接返回
+        3. 兜底:抓取任何含目录分隔符且以 .pdf 结尾的片段
+        """
+        if not result_text:
+            return None
+
+        text = result_text.strip()
+
+        # 1. 整段就是纯路径
+        if text.endswith(".pdf") and "\n" not in text:
+            return text
+
+        # 2. 逐行从后往前找
+        for line in reversed(text.splitlines()):
+            line = line.strip()
+            if not line:
+                continue
+            # 去掉 "工具 'xxx' 执行结果:" 之类的中英文冒号前缀
+            line = re.sub(r'^[^:\n]*[::]\s*', '', line)
+            if line.endswith(".pdf"):
+                return line
+            # 行末包含路径的情况,如 "Downloaded to: xxx.pdf"
+            m = re.search(r'([^\s:"\']+\.pdf)\s*$', line)
+            if m:
+                return m.group(1)
+
+        # 3. 兜底:任何含目录分隔符且以 .pdf 结尾的片段
+        #    要求路径里至少出现一个 \ 或 / 且不是开头就 /
+        m = re.search(
+            r'([A-Za-z]:[\\/][^\s:"\']+\.pdf'  # Windows 绝对路径
+            r'|[^\s:"\'/\\]+[\\/][^\s:"\']+\.pdf)'  # 相对路径(至少一级目录)
+            , text
+        )
+        if m:
+            return m.group(1)
+
+        return None
+
+    def _index_if_downloaded(self, paper: Dict[str, Any]) -> None:
+        """若已下载 PDF,则加入 RAG 索引"""
+        pdf_path = paper.get("pdf_path")
+        if not pdf_path or not Path(pdf_path).exists():
+            paper["indexed"] = False
+            return
+
+        doi = (paper.get("doi") or "").strip()
+        title = (paper.get("title") or "").strip()
+        paper_id = (paper.get("paper_id") or "").strip()
+        stable_id = self._make_stable_id(doi, paper_id, title)
+        if not stable_id:
+            paper["indexed"] = False
+            return
+
+        paper["stable_id"] = stable_id
+
+        index_result = self.library.index_paper(
+            pdf_path=pdf_path,
+            paper_id=stable_id,
+            metadata={
+                "title": title,
+                "doi": doi,
+                "source": paper.get("source"),
+                "source_id": paper_id,
+                "year": paper.get("year"),
+                "venue": paper.get("venue"),
+            },
+        )
+        paper["indexed"] = bool(index_result.get("success"))
+        paper["chunks"] = index_result.get("chunks", 0)
+
+    @staticmethod
+    def _make_stable_id(doi: str, source_id: str, title: str) -> Optional[str]:
+        if doi:
+            return f"doi_{hashlib.md5(doi.lower().encode()).hexdigest()[:16]}"
+        if source_id:
+            safe = re.sub(r"[^\w\-]", "_", source_id)[:40]
+            return f"sid_{safe}"
+        if title:
+            return f"title_{hashlib.md5(title.lower().encode()).hexdigest()[:16]}"
+        return None
+
+    # ------------------------------------------------------------------
+    @staticmethod
+    def _parse_papers(response: str) -> List[Dict[str, Any]]:
+        if not response:
+            return []
+
+        try:
+            data = json.loads(response)
+            if isinstance(data, dict) and isinstance(data.get("papers"), list):
+                return [p for p in data["papers"] if isinstance(p, dict)]
+        except json.JSONDecodeError:
+            pass
+
+        start, end = response.find("{"), response.rfind("}")
+        if start != -1 and end > start:
+            try:
+                data = json.loads(response[start:end + 1])
+                if isinstance(data, dict) and isinstance(data.get("papers"), list):
+                    return [p for p in data["papers"] if isinstance(p, dict)]
+            except json.JSONDecodeError:
+                pass
+
+        m = re.search(r"```json\s*(\{.*?\})\s*```", response, re.DOTALL)
+        if m:
+            try:
+                data = json.loads(m.group(1))
+                if isinstance(data, dict) and isinstance(data.get("papers"), list):
+                    return [p for p in data["papers"] if isinstance(p, dict)]
+            except json.JSONDecodeError:
+                pass
+
+        logger.warning("未能从检索 Agent 输出中解析 papers")
+        return []
+
+    @staticmethod
+    def _deduplicate(papers: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+        seen, unique = set(), []
+        for p in papers:
+            doi = (p.get("doi") or "").strip().lower()
+            title = re.sub(r"\s+", " ", (p.get("title") or "").strip().lower())
+            key = doi or title
+            if not key or key in seen:
+                continue
+            seen.add(key)
+            unique.append(p)
+        return unique
+
+    # ------------------------------------------------------------------
+    def list_tools(self) -> List[str]:
+        return self._agent.list_tools() if self._agent else []
+
+    def library_stats(self) -> Dict[str, Any]:
+        return self.library.stats()

+ 98 - 0
Co-creation-projects/Lemoween-PaperAssistant/config.py

@@ -0,0 +1,98 @@
+"""论文撰写助手配置
+
+LLM 由 HelloAgentsLLM 自动检测;Qdrant/Neo4j/Embedding 由 RAGTool/MemoryTool 内部读取。
+本模块只管理应用层配置。
+"""
+import os
+from enum import Enum
+from typing import Any, List, Optional
+
+from pydantic import BaseModel
+
+
+class PaperType(str, Enum):
+    CONFERENCE = "conference"
+    JOURNAL = "journal"
+    THESIS = "thesis"
+
+
+class CitationStyle(str, Enum):
+    GB7714 = "gb7714"
+    APA = "apa"
+
+
+class Configuration(BaseModel):
+    """应用层配置"""
+
+    # ---------- 论文设置 ----------
+    paper_type: PaperType = PaperType.CONFERENCE
+    citation_style: CitationStyle = CitationStyle.GB7714
+    target_sections: int = 5
+    target_words_per_section: int = 1000
+    max_references_per_section: int = 5
+    max_review_rounds: int = 2
+
+    # ---------- Paper Search MCP ----------
+    paper_search_mcp_command: str = "uvx,paper-search-mcp"
+    paper_search_mcp_prefix: str = "papersearch"
+
+    # ---------- 论文库 ----------
+    pdf_download_enabled: bool = True
+    max_pdf_size_mb: int = 50
+    paper_library_path: str = "./workspace/paper_library"
+    paper_library_rag_namespace: Optional[str] = None
+
+    # ---------- 笔记与记忆 ----------
+    enable_notes: bool = True
+    notes_workspace: str = "./workspace/paper_notes"
+    enable_memory: bool = True
+    memory_user_id: str = "paper_author"
+
+    # ---------- 其他 ----------
+    strip_thinking_tokens: bool = True
+
+    @classmethod
+    def from_env(cls, overrides: Optional[dict] = None) -> "Configuration":
+        raw: dict[str, Any] = {}
+
+        for name in cls.model_fields.keys():
+            key = name.upper()
+            if key in os.environ:
+                raw[name] = os.environ[key]
+
+        aliases = {
+            "paper_type": os.getenv("PAPER_TYPE"),
+            "citation_style": os.getenv("CITATION_STYLE"),
+            "target_sections": os.getenv("TARGET_SECTIONS"),
+            "target_words_per_section": os.getenv("TARGET_WORDS_PER_SECTION"),
+            "max_references_per_section": os.getenv("MAX_REFERENCES_PER_SECTION"),
+            "max_review_rounds": os.getenv("MAX_REVIEW_ROUNDS"),
+            "paper_search_mcp_command": os.getenv("PAPER_SEARCH_MCP_COMMAND"),
+            "paper_search_mcp_prefix": os.getenv("PAPER_SEARCH_MCP_PREFIX"),
+            "pdf_download_enabled": os.getenv("PDF_DOWNLOAD_ENABLED"),
+            "max_pdf_size_mb": os.getenv("MAX_PDF_SIZE_MB"),
+            "paper_library_path": os.getenv("PAPER_LIBRARY_PATH"),
+            "paper_library_rag_namespace": os.getenv("PAPER_LIBRARY_RAG_NAMESPACE"),
+            "enable_notes": os.getenv("ENABLE_NOTES"),
+            "notes_workspace": os.getenv("NOTES_WORKSPACE"),
+            "enable_memory": os.getenv("ENABLE_MEMORY"),
+            "memory_user_id": os.getenv("MEMORY_USER_ID"),
+            "strip_thinking_tokens": os.getenv("STRIP_THINKING_TOKENS"),
+        }
+        for key, value in aliases.items():
+            if value is not None:
+                raw.setdefault(key, value)
+
+        if overrides:
+            for key, value in overrides.items():
+                if value is not None:
+                    raw[key] = value
+
+        return cls(**raw)
+
+    def resolve_paper_search_mcp_command(self) -> Optional[List[str]]:
+        """把逗号分隔的命令字符串解析为列表"""
+        raw = (self.paper_search_mcp_command or "").strip()
+        if not raw:
+            return None
+        return [p.strip() for p in raw.split(",") if p.strip()]

+ 97 - 0
Co-creation-projects/Lemoween-PaperAssistant/main.py

@@ -0,0 +1,97 @@
+"""论文撰写助手入口"""
+import logging
+import sys
+from pathlib import Path
+
+from dotenv import load_dotenv
+
+logging.basicConfig(
+    level=logging.INFO,
+    format="%(asctime)s | %(levelname)-5s | %(name)s | %(message)s",
+    datefmt="%H:%M:%S",
+)
+
+load_dotenv()
+
+from agent import PaperAssistantAgent
+from config import Configuration
+from hello_agents import HelloAgentsLLM
+
+
+def main():
+    topic = sys.argv[1] if len(sys.argv) > 1 else (
+        "大语言模型在学术写作辅助中的应用与挑战"
+    )
+
+    print("=" * 70)
+    print(f"📝 论文主题:{topic}")
+    print("=" * 70)
+
+    config = Configuration.from_env()
+
+    # LLM 信息从 HelloAgentsLLM 自动检测结果中读取
+    try:
+        llm = HelloAgentsLLM(temperature=0.0)
+        llm_provider = llm.provider
+        llm_model = llm.model
+    except Exception as exc:
+        llm_provider = "未配置"
+        llm_model = f"(错误:{exc})"
+
+    # Paper Search MCP 命令
+    mcp_command = config.resolve_paper_search_mcp_command()
+
+    print(f"\n配置摘要:")
+    print(f"  LLM Provider   : {llm_provider}")
+    print(f"  LLM Model      : {llm_model}")
+    print(f"  论文类型        : {config.paper_type.value}")
+    print(f"  引用格式        : {config.citation_style.value}")
+    print(f"  目标章节数      : {config.target_sections}")
+    print(f"  每章目标字数    : {config.target_words_per_section}")
+    print(f"  每章参考文献    : {config.max_references_per_section}")
+    print(f"  论文库路径      : {config.paper_library_path}")
+    print(f"  Notes 工作区    : {config.notes_workspace}")
+    print(f"  Memory 用户     : {config.memory_user_id}")
+    print(f"  PDF 下载        : {config.pdf_download_enabled}")
+    print(f"  Paper Search MCP: {mcp_command or '(未配置)'}")
+
+    assistant = PaperAssistantAgent(config=config)
+    result = assistant.run(topic)
+
+    # 输出
+    print("\n" + "=" * 70)
+    print("📊 撰写完成")
+    print("=" * 70)
+    print(f"  论文章节数      : {len(result.sections)}")
+    print(f"  参考文献总数    : {len(result.references)}")
+    print(f"  已下载 PDF      : "
+          f"{sum(1 for r in result.references if r.get('indexed'))}")
+    print(f"  审校意见长度    : {len(result.review_notes)} 字")
+
+    stats = result.library_stats
+    print(f"  论文库统计:")
+    print(f"    - 命名空间    : {stats.get('rag_namespace')}")
+    print(f"    - 已索引论文  : {stats.get('indexed_papers')}")
+
+    # 保存
+    output_dir = Path("./workspace/output")
+    output_dir.mkdir(parents=True, exist_ok=True)
+
+    safe_topic = "".join(c for c in topic[:30] if c.isalnum() or c in "-_")
+    paper_file = output_dir / f"paper_{safe_topic}.md"
+    review_file = output_dir / f"review_{safe_topic}.md"
+
+    paper_file.write_text(result.paper_markdown, encoding="utf-8")
+    review_file.write_text(result.review_notes, encoding="utf-8")
+
+    print(f"\n📄 论文已保存:{paper_file}")
+    print(f"📄 审校意见:  {review_file}")
+    print("\n" + "=" * 70)
+    print("论文预览(前 2000 字):")
+    print("=" * 70)
+    print(result.paper_markdown[:2000])
+    print("..." if len(result.paper_markdown) > 2000 else "")
+
+
+if __name__ == "__main__":
+    main()

+ 48 - 0
Co-creation-projects/Lemoween-PaperAssistant/models.py

@@ -0,0 +1,48 @@
+"""数据模型"""
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+
+
+@dataclass(kw_only=True)
+class PaperSection:
+    """论文章节(对标第十四章的 TodoItem)"""
+    id: int
+    title: str
+    intent: str
+    keywords: List[str] = field(default_factory=list)
+    target_words: int = 800
+
+    status: str = "pending"
+    content: Optional[str] = None
+    references: List[Dict[str, Any]] = field(default_factory=list)
+    review_feedback: Optional[str] = None
+
+    note_id: Optional[str] = None
+    note_path: Optional[str] = None
+    stream_token: Optional[str] = None
+
+
+@dataclass(kw_only=True)
+class PaperState:
+    """论文撰写全局状态(对标第十四章的 SummaryState)"""
+    research_topic: str
+    paper_title: Optional[str] = None
+    paper_type: str = "conference"
+    citation_style: str = "gb7714"
+
+    sections: List[PaperSection] = field(default_factory=list)
+    all_references: List[Dict[str, Any]] = field(default_factory=list)
+    review_notes: str = ""
+    final_paper: Optional[str] = None
+
+    report_note_id: Optional[str] = None
+    report_note_path: Optional[str] = None
+
+
+@dataclass(kw_only=True)
+class PaperStateOutput:
+    paper_markdown: str
+    sections: List[PaperSection]
+    references: List[Dict[str, Any]]
+    review_notes: str
+    library_stats: Dict[str, Any] = field(default_factory=dict)

+ 155 - 0
Co-creation-projects/Lemoween-PaperAssistant/prompts.py

@@ -0,0 +1,155 @@
+"""所有 Agent 的系统提示词"""
+from datetime import datetime
+
+
+def get_current_date() -> str:
+    return datetime.now().strftime("%Y年%m月%d日")
+
+
+# ============================================================
+# 1. 论文规划专家
+# ============================================================
+paper_planner_system_prompt = """
+你是一名学术论文结构设计专家,请把研究主题拆解为一组有限、互补的论文章节。
+
+<GOAL>
+1. 结合研究主题梳理 3-5 个最关键的章节(含引言、相关工作、方法、实验/分析、结论);
+2. 每个章节需明确写作意图,并给出适宜的中英文检索关键词;
+3. 章节之间要避免内容重叠,整体覆盖论文的完整逻辑;
+4. 在创建或更新章节时,必须调用 `note` 工具同步信息。
+</GOAL>
+
+<NOTE_COLLAB>
+- 为每个章节调用 `note` 工具创建结构化笔记,统一使用 JSON 参数格式:
+  - 创建示例:`[TOOL_CALL:note:{"action":"create","task_id":1,"title":"章节 1: <标题>","note_type":"task_state","tags":["paper","section_1"],"content":"请记录章节意图、关键词、状态"}]`
+  - 更新示例:`[TOOL_CALL:note:{"action":"update","note_id":"<现有ID>","task_id":1,"title":"章节 1: <标题>","note_type":"task_state","tags":["paper","section_1"],"content":"...新增内容..."}]`
+- `tags` 必须包含 `paper` 与 `section_{task_id}`,以便其他 Agent 查找。
+</NOTE_COLLAB>
+"""
+
+paper_planner_instructions = """
+<CONTEXT>
+当前日期:{current_date}
+研究主题:{research_topic}
+论文类型:{paper_type}
+目标章节数:{target_sections}
+每章目标字数:{target_words_per_section}
+</CONTEXT>
+
+<FORMAT>
+请严格以 JSON 格式回复:
+{{
+  "paper_title": "论文拟用标题",
+  "sections": [
+    {{
+      "title": "章节标题",
+      "intent": "该章节要解决的核心问题,用1-2句描述",
+      "keywords": ["english_keyword_1", "english_keyword_2"],
+      "target_words": 800
+    }}
+  ]
+}}
+</FORMAT>
+
+先用 note 工具为每个章节创建/更新笔记,再输出上述 JSON。
+"""
+
+
+# ============================================================
+# 2. 文献检索专家(Paper Search MCP)
+# 说明:本 Agent 只负责"检索",下载由 Python 层统一执行
+# ============================================================
+literature_search_system_prompt = """
+你是一名学术文献检索专家。你的任务是为论文章节检索高质量的学术文献。
+
+## 已装配的检索工具(来自 Paper Search MCP)
+{tools_placeholder}
+
+## 工作原则
+1. **必须调用 `{prefix}_search_papers`** 完成跨源检索,参数(JSON 格式):
+   - `query`(必填):英文检索关键词
+   - `sources`(可选):逗号分隔的来源列表,推荐
+     `"arxiv,semantic,crossref,openalex,dblp"`;
+   - `max_results_per_source`(可选):每源返回数,建议 5
+2. **不要调用任何 download 工具**——下载由系统在检索完成后自动执行;
+3. **禁止引入任何网页链接**,只能引用检索工具返回的论文;
+4. 检索完成后,**只输出 JSON**,不要输出任何解释性文字。
+
+## 输出格式(严格 JSON)
+{{"papers": [
+  {{
+    "title": "...",
+    "authors": ["...", "..."],
+    "year": 2024,
+    "venue": "...",
+    "doi": "...",          # 有则填,无则空字符串
+    "source": "arxiv",     # 必填:arxiv / semantic / crossref / openalex / dblp
+    "paper_id": "..."      # 必填:源的原始 ID(arxiv id / S2 id / DOI 等)
+  }}
+]}}
+"""
+
+
+# ============================================================
+# 3. 章节撰写专家
+# ============================================================
+section_writer_system_prompt = """
+你是一名学术论文写作专家。你的任务是根据章节意图与已检索文献撰写章节正文。
+
+<REQUIREMENTS>
+1. 语言正式、客观,使用学术写作风格;
+2. 每个论点必须有文献支撑,使用 [序号] 或 [Author, Year] 格式引用;
+3. 引用只能来自本会话检索到的学术文献,禁止引入网页链接;
+4. 写作前可调用 search_paper_library 检索已下载论文的原文细节;
+5. 引用完成后调用 format_citation 生成规范引用条目;
+6. 章节字数控制在目标字数 ±20% 内;
+7. 撰写前调用 note(action=read) 读取章节笔记,撰写完成后调用 note(action=update) 更新进度。
+</REQUIREMENTS>
+
+<OUTPUT>
+直接输出 Markdown 格式的章节正文(不含章节标题)。
+</OUTPUT>
+"""
+
+
+# ============================================================
+# 4. 论文审校专家
+# ============================================================
+paper_reviewer_system_prompt = """
+你是一名严格的学术论文审稿人。你的任务是对论文草稿进行审校。
+
+<REVIEW_DIMENSIONS>
+1. 论证逻辑:论点是否有充分依据,逻辑链是否严密;
+2. 引用规范:引用是否对应真实文献,是否存在未标注来源的论断;
+3. 术语一致性:全文术语是否统一,缩写是否有定义;
+4. 章节连贯:章节之间的过渡是否自然;
+5. 方法可复现性:方法/实验部分是否提供了足够细节。
+</REVIEW_DIMENSIONS>
+
+<OUTPUT>
+审校意见分为三部分:
+- 【必须修改】Blocking 问题(列出具体位置)
+- 【建议修改】Non-blocking 问题
+- 【整体评价】合格 / 需修改 / 不合格
+</OUTPUT>
+"""
+
+
+# ============================================================
+# 5. 报告汇总专家
+# ============================================================
+report_assembler_system_prompt = """
+你是一名学术论文编辑。你的任务是将各章节草稿整合为完整论文。
+
+<REQUIREMENTS>
+1. 添加论文标题与摘要(200-300 字,概括研究背景、方法、主要发现);
+2. 按照论文章节顺序排列(引言→相关工作→方法→实验→结论);
+3. 合并所有章节的参考文献,去重后按引用顺序编号;
+4. 使用 {citation_style} 格式生成参考文献列表;
+5. 使用 Markdown 格式输出。
+</REQUIREMENTS>
+
+<OUTPUT>
+完整的 Markdown 格式论文,包含:标题、摘要、正文各章节、参考文献。
+</OUTPUT>
+"""

+ 42 - 0
Co-creation-projects/Lemoween-PaperAssistant/requirements.txt

@@ -0,0 +1,42 @@
+# ============================================================
+# 核心框架
+# ============================================================
+hello-agents[all]==0.2.8
+
+# ============================================================
+# 学术检索(供工具层使用)
+# ============================================================
+arxiv>=2.1.0
+requests>=2.31.0
+
+# ============================================================
+# 配置与数据模型
+# ============================================================
+python-dotenv>=1.0.0
+pydantic>=2.5.0
+
+# ============================================================
+# 文本处理(spaCy 模型需单独下载)
+# ============================================================
+spacy>=3.7.0
+
+# ============================================================
+# 可选:如使用 dashscope 云端 Embedding
+# ============================================================
+# dashscope>=1.20.0
+
+# ============================================================
+# 可选:本地 Embedding 回退(当 EMBED_API_KEY 未配置时自动启用)
+# ============================================================
+# sentence-transformers>=2.5.0
+# torch>=2.0.0
+
+# ============================================================
+# 可选:Qdrant 客户端(如 hello-agents[all] 未包含)
+# ============================================================
+# qdrant-client>=1.7.0
+
+# ============================================================
+# 可选:Neo4j 客户端(如 hello-agents[all] 未包含)
+# ============================================================
+# neo4j>=5.14.0

+ 1 - 0
Co-creation-projects/Lemoween-PaperAssistant/services/__init__.py

@@ -0,0 +1 @@
+"""论文撰写助手的领域服务层"""

+ 57 - 0
Co-creation-projects/Lemoween-PaperAssistant/services/assembler.py

@@ -0,0 +1,57 @@
+"""论文汇总服务"""
+from typing import Callable, List
+
+from hello_agents import ToolAwareSimpleAgent
+
+from config import Configuration
+from models import PaperSection, PaperState
+from utils import strip_thinking_tokens, strip_tool_calls
+
+
+class ReportAssemblyService:
+    """调用汇总 Agent 生成最终论文"""
+
+    def __init__(
+        self,
+        agent_factory: Callable[[], ToolAwareSimpleAgent],
+        config: Configuration,
+    ):
+        self._agent_factory = agent_factory
+        self._config = config
+
+    def assemble(
+        self,
+        state: PaperState,
+        sections: List[PaperSection],
+        review_notes: str,
+    ) -> str:
+        section_blocks = []
+        for s in sections:
+            section_blocks.append(f"## {s.title}\n\n{s.content or '(暂无内容)'}\n")
+
+        all_refs = [r for s in sections for r in s.references]
+        ref_lines = [
+            f"[{i}] {ref.get('citation') or ref.get('title', '')}"
+            for i, ref in enumerate(all_refs, start=1)
+        ]
+
+        prompt = (
+            f"论文题目:{state.paper_title or state.research_topic}\n"
+            f"研究主题:{state.research_topic}\n"
+            f"引用格式:{state.citation_style}\n\n"
+            f"章节草稿:\n{''.join(section_blocks)}\n\n"
+            f"参考文献条目:\n" + "\n".join(ref_lines) + "\n\n"
+            f"审校意见:\n{review_notes}\n\n"
+            f"请整合为一份完整论文(标题、摘要、正文、参考文献)。"
+        )
+
+        agent = self._agent_factory()
+        try:
+            response = agent.run(prompt)
+        finally:
+            agent.clear_history()
+
+        paper = response.strip()
+        if self._config.strip_thinking_tokens:
+            paper = strip_thinking_tokens(paper)
+        return strip_tool_calls(paper).strip()

+ 175 - 0
Co-creation-projects/Lemoween-PaperAssistant/services/paper_library.py

@@ -0,0 +1,175 @@
+"""论文库服务:包装官方 RAGTool + MemoryTool + NoteTool
+
+    PDF → MarkItDown → Markdown → 智能分块 → 向量化 → Qdrant 存储
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+from hello_agents.tools import RAGTool
+
+logger = logging.getLogger(__name__)
+
+
+class PaperLibraryService:
+    """论文库:管理 PDF 的 RAG 索引与检索"""
+
+    def __init__(
+        self,
+        library_path: str = "./workspace/paper_library",
+        rag_namespace: Optional[str] = None,
+        pdf_dir: Optional[str] = None,
+    ):
+        self.library_path = Path(library_path)
+        self.library_path.mkdir(parents=True, exist_ok=True)
+
+        self.pdf_dir = Path(pdf_dir) if pdf_dir else self.library_path / "pdfs"
+        self.pdf_dir.mkdir(parents=True, exist_ok=True)
+
+        self.rag_dir = self.library_path / "rag"
+        self.rag_dir.mkdir(parents=True, exist_ok=True)
+
+        if not rag_namespace:
+            h = hashlib.md5(str(self.library_path.resolve()).encode()).hexdigest()[:8]
+            rag_namespace = f"papers_{h}"
+        self.rag_namespace = rag_namespace
+
+        # 参照第八章使用 RAGTool
+        try:
+            self.rag_tool = RAGTool(
+                knowledge_base_path=str(self.rag_dir),
+                collection_name="paper_library",
+                rag_namespace=rag_namespace,
+            )
+            logger.info("PaperLibrary RAGTool 就绪: namespace=%s", rag_namespace)
+        except Exception as exc:
+            logger.exception("RAGTool 初始化失败: %s", exc)
+            self.rag_tool = None
+
+        self._manifest_path = self.rag_dir / "index_manifest.json"
+        self._manifest: Dict[str, Dict[str, Any]] = self._load_manifest()
+
+    # ------------------------------------------------------------------
+    def index_paper(
+        self,
+        pdf_path: str,
+        paper_id: str,
+        metadata: Optional[Dict[str, Any]] = None,
+        chunk_size: int = 1000,
+        chunk_overlap: int = 200,
+    ) -> Dict[str, Any]:
+        """将下载的 PDF 加入 RAG 索引(内部走 MarkItDown → Markdown → 分块 → 向量化)"""
+        if not self.rag_tool:
+            return {"success": False, "error": "RAGTool 未初始化"}
+
+        if paper_id in self._manifest:
+            return {"success": True, "skipped": True, "paper_id": paper_id,
+                    "chunks": self._manifest[paper_id].get("chunks", 0)}
+
+        path = Path(pdf_path)
+        if not path.exists():
+            return {"success": False, "error": f"PDF 不存在: {pdf_path}"}
+
+        try:
+            # 参照第八章 8.4.2 的调用方式
+            result = self.rag_tool.execute(
+                "add_document",
+                file_path=str(path),
+                document_id=paper_id,
+                chunk_size=chunk_size,
+                chunk_overlap=chunk_overlap,
+            )
+
+            if isinstance(result, dict):
+                success = result.get("success", True)
+                chunks = result.get("chunks") or result.get("chunk_count") or 0
+            else:
+                success = True
+                chunks = 0
+
+            if success:
+                self._manifest[paper_id] = {
+                    "pdf_path": str(path),
+                    "chunks": chunks,
+                    "indexed_at": datetime.now().isoformat(),
+                    "metadata": metadata or {},
+                }
+                self._save_manifest()
+                logger.info("索引 %s 成功 (%d chunks)", paper_id, chunks)
+
+            return {"success": success, "paper_id": paper_id, "chunks": chunks}
+
+        except Exception as exc:
+            logger.exception("索引 %s 失败", paper_id)
+            return {"success": False, "error": str(exc)}
+
+    # ------------------------------------------------------------------
+    def search(
+        self,
+        query: str,
+        limit: int = 5,
+        min_score: float = 0.1,
+        enable_advanced: bool = False,
+    ) -> str:
+        """检索论文库(参照第八章 8.4.3 的 RAGTool.execute("search") 方式)"""
+        if not self.rag_tool:
+            return "❌ RAGTool 未初始化"
+        try:
+            kwargs: Dict[str, Any] = {
+                "query": query, "limit": limit, "min_score": min_score,
+            }
+            if enable_advanced:
+                kwargs.update({
+                    "enable_advanced_search": True,
+                    "enable_mqe": True,
+                    "enable_hyde": True,
+                })
+            result = self.rag_tool.execute("search", **kwargs)
+            return str(result) if not isinstance(result, str) else result
+        except Exception as exc:
+            logger.exception("论文库检索失败")
+            return f"❌ 检索失败: {exc}"
+
+    def ask(self, question: str, limit: int = 5) -> str:
+        """基于论文库直接回答(RAG 增强生成,参照第八章 8.4.3)"""
+        if not self.rag_tool:
+            return "❌ RAGTool 未初始化"
+        try:
+            result = self.rag_tool.execute("ask", question=question, limit=limit)
+            return str(result) if not isinstance(result, str) else result
+        except Exception as exc:
+            return f"❌ 问答失败: {exc}"
+
+    def stats(self) -> Dict[str, Any]:
+        return {
+            "library_path": str(self.library_path),
+            "rag_namespace": self.rag_namespace,
+            "indexed_papers": len(self._manifest),
+            "papers": [
+                {"paper_id": pid, "chunks": info.get("chunks", 0),
+                 "indexed_at": info.get("indexed_at")}
+                for pid, info in self._manifest.items()
+            ],
+        }
+
+    # ------------------------------------------------------------------
+    def _load_manifest(self) -> Dict[str, Dict[str, Any]]:
+        if self._manifest_path.exists():
+            try:
+                with open(self._manifest_path, "r", encoding="utf-8") as f:
+                    return json.load(f)
+            except Exception as exc:
+                logger.warning("manifest 读取失败: %s", exc)
+        return {}
+
+    def _save_manifest(self) -> None:
+        try:
+            with open(self._manifest_path, "w", encoding="utf-8") as f:
+                json.dump(self._manifest, f, ensure_ascii=False, indent=2)
+        except Exception as exc:
+            logger.warning("manifest 写入失败: %s", exc)

+ 90 - 0
Co-creation-projects/Lemoween-PaperAssistant/services/planner.py

@@ -0,0 +1,90 @@
+"""章节规划服务"""
+import json
+import logging
+from typing import Any, List
+
+from hello_agents import ToolAwareSimpleAgent
+
+from config import Configuration
+from models import PaperSection, PaperState
+from prompts import get_current_date, paper_planner_instructions
+from utils import strip_thinking_tokens, strip_tool_calls
+
+logger = logging.getLogger(__name__)
+
+
+class PlanningService:
+    """封装规划 Agent,产出结构化章节列表"""
+
+    def __init__(self, planner_agent: ToolAwareSimpleAgent, config: Configuration):
+        self._agent = planner_agent
+        self._config = config
+
+    def plan_outline(self, state: PaperState) -> List[PaperSection]:
+        prompt = paper_planner_instructions.format(
+            current_date=get_current_date(),
+            research_topic=state.research_topic,
+            paper_type=state.paper_type,
+            target_sections=self._config.target_sections,
+            target_words_per_section=self._config.target_words_per_section,
+        )
+        response = self._agent.run(prompt)
+        self._agent.clear_history()
+
+        logger.info("Planner raw output (truncated): %s", response[:500])
+
+        payload = self._extract_payload(response)
+        if payload.get("paper_title"):
+            state.paper_title = str(payload["paper_title"]).strip()
+
+        sections: List[PaperSection] = []
+        for idx, item in enumerate(payload.get("sections") or [], start=1):
+            if not isinstance(item, dict):
+                continue
+            title = str(item.get("title") or f"章节{idx}").strip()
+            intent = str(item.get("intent") or "").strip()
+            keywords = item.get("keywords") or []
+            if isinstance(keywords, str):
+                keywords = [keywords]
+            target_words = int(item.get("target_words")
+                               or self._config.target_words_per_section)
+            sections.append(PaperSection(
+                id=idx, title=title, intent=intent,
+                keywords=list(keywords), target_words=target_words,
+            ))
+
+        return sections
+
+    @staticmethod
+    def create_fallback_sections() -> List[PaperSection]:
+        """规划失败时的回退章节(参照第十四章 create_fallback_task)"""
+        defaults = [
+            ("Introduction", "介绍研究背景、问题与贡献", ["background", "motivation"]),
+            ("Related Work", "梳理领域已有研究与差距", ["related work", "survey"]),
+            ("Method", "阐述研究方法与实现细节",
+             ["method", "approach", "algorithm"]),
+            ("Experiments", "呈现实验设计与结果分析",
+             ["experiment", "evaluation", "benchmark"]),
+            ("Conclusion", "总结贡献与未来方向",
+             ["conclusion", "future work"]),
+        ]
+        return [
+            PaperSection(id=i + 1, title=t, intent=it, keywords=kw)
+            for i, (t, it, kw) in enumerate(defaults)
+        ]
+
+    def _extract_payload(self, response: str) -> dict[str, Any]:
+        """从 Agent 响应中提取 JSON(参照第十四章 PlanningService._extract_json)"""
+        text = response.strip()
+        if self._config.strip_thinking_tokens:
+            text = strip_thinking_tokens(text)
+        text = strip_tool_calls(text).strip()
+
+        start = text.find("{")
+        end = text.rfind("}")
+        if start != -1 and end > start:
+            try:
+                return json.loads(text[start:end + 1])
+            except json.JSONDecodeError:
+                pass
+        return {}

+ 39 - 0
Co-creation-projects/Lemoween-PaperAssistant/services/reviewer.py

@@ -0,0 +1,39 @@
+"""论文审校服务"""
+from typing import Callable
+
+from hello_agents import ToolAwareSimpleAgent
+
+from config import Configuration
+from models import PaperState
+from utils import strip_thinking_tokens, strip_tool_calls
+
+
+class ReviewService:
+    """调用审校 Agent 对论文草稿进行审阅"""
+
+    def __init__(
+        self,
+        agent_factory: Callable[[], ToolAwareSimpleAgent],
+        config: Configuration,
+    ):
+        self._agent_factory = agent_factory
+        self._config = config
+
+    def review(self, state: PaperState, full_draft: str) -> str:
+        prompt = (
+            f"论文题目:{state.paper_title or state.research_topic}\n"
+            f"引用格式:{state.citation_style}\n\n"
+            f"论文草稿:\n{full_draft[:8000]}\n\n"
+            f"请从逻辑、引用、术语、连贯性和可复现性五个维度审校。"
+        )
+
+        agent = self._agent_factory()
+        try:
+            response = agent.run(prompt)
+        finally:
+            agent.clear_history()
+
+        notes = response.strip()
+        if self._config.strip_thinking_tokens:
+            notes = strip_thinking_tokens(notes)
+        return strip_tool_calls(notes).strip()

+ 70 - 0
Co-creation-projects/Lemoween-PaperAssistant/services/tool_events.py

@@ -0,0 +1,70 @@
+"""工具调用事件追踪"""
+from __future__ import annotations
+
+import logging
+import re
+from pathlib import Path
+from threading import Lock
+from typing import Any, Callable, Optional
+
+logger = logging.getLogger(__name__)
+
+
+class ToolCallTracker:
+    """收集 Agent 工具调用事件,供日志与前端展示"""
+
+    def __init__(self, notes_workspace: Optional[str] = None) -> None:
+        self._notes_workspace = notes_workspace
+        self._events: list[dict[str, Any]] = []
+        self._cursor = 0
+        self._lock = Lock()
+        self._event_sink: Optional[Callable[[dict[str, Any]], None]] = None
+
+    def record(self, payload: dict[str, Any]) -> None:
+        agent_name = str(payload.get("agent_name") or "unknown")
+        tool_name = str(payload.get("tool_name") or "unknown")
+        parameters = payload.get("parsed_parameters") or {}
+        if not isinstance(parameters, dict):
+            parameters = {}
+        result_text = str(payload.get("result") or "")
+
+        note_id = None
+        if tool_name == "note":
+            note_id = parameters.get("note_id") or self._extract_note_id(result_text)
+
+        event = {
+            "id": len(self._events) + 1,
+            "agent": agent_name,
+            "tool": tool_name,
+            "parameters": parameters,
+            "result": result_text[:500],
+            "note_id": note_id,
+        }
+        with self._lock:
+            self._events.append(event)
+
+        logger.info("Tool call: agent=%s tool=%s note_id=%s",
+                    agent_name, tool_name, note_id)
+
+        if self._event_sink:
+            self._event_sink(event)
+
+    def drain(self) -> list[dict[str, Any]]:
+        with self._lock:
+            new = self._events[self._cursor:]
+            self._cursor = len(self._events)
+        return new
+
+    def set_event_sink(self, sink: Optional[Callable[[dict[str, Any]], None]]) -> None:
+        self._event_sink = sink
+
+    def as_dicts(self) -> list[dict[str, Any]]:
+        with self._lock:
+            return list(self._events)
+
+    @staticmethod
+    def _extract_note_id(response: str) -> Optional[str]:
+        if not response:
+            return None
+        match = re.search(r"ID:\s*([^\n]+)", response)
+        return match.group(1).strip() if match else None

+ 71 - 0
Co-creation-projects/Lemoween-PaperAssistant/services/writer.py

@@ -0,0 +1,71 @@
+"""章节撰写服务"""
+import logging
+from typing import Any, Callable, Dict, List
+
+from hello_agents import ToolAwareSimpleAgent
+
+from config import Configuration
+from models import PaperSection, PaperState
+from utils import strip_thinking_tokens, strip_tool_calls
+
+logger = logging.getLogger(__name__)
+
+
+class SectionWritingService:
+    """调用写作 Agent 完成章节草稿"""
+
+    def __init__(
+        self,
+        agent_factory: Callable[[], ToolAwareSimpleAgent],
+        config: Configuration,
+    ):
+        self._agent_factory = agent_factory
+        self._config = config
+
+    def write_section(
+        self,
+        state: PaperState,
+        section: PaperSection,
+        references: List[Dict[str, Any]],
+        previous_context: str = "",
+    ) -> str:
+        refs_block = self._format_references(references)
+
+        prompt = (
+            f"论文题目:{state.paper_title or state.research_topic}\n"
+            f"章节标题:{section.title}\n"
+            f"章节意图:{section.intent}\n"
+            f"目标字数:{section.target_words}\n\n"
+            f"## 可用文献(引用必须来自以下列表)\n{refs_block}\n\n"
+            f"## 已完成章节的上下文\n{previous_context[-800:]}\n\n"
+            f"## 撰写要求\n"
+            f"1. 写作过程中如需了解论文原文细节,**调用 search_paper_library 工具**;\n"
+            f"2. 引用必须来自上方文献列表,禁止引入网页链接;\n"
+            f"3. 使用 format_citation 生成规范引用条目;\n"
+            f"4. 撰写完成后将章节草稿写入笔记(note 工具)。"
+        )
+
+        agent = self._agent_factory()
+        try:
+            response = agent.run(prompt)
+        finally:
+            agent.clear_history()
+
+        content = response.strip()
+        if self._config.strip_thinking_tokens:
+            content = strip_thinking_tokens(content)
+        return strip_tool_calls(content).strip()
+
+    @staticmethod
+    def _format_references(references: List[Dict[str, Any]]) -> str:
+        if not references:
+            return "(暂无检索到的文献)"
+        lines = []
+        for i, ref in enumerate(references, start=1):
+            lines.append(
+                f"[{i}] {ref.get('title', '')} "
+                f"({ref.get('year', '')}) — {ref.get('venue', '')} "
+                f"DOI: {ref.get('doi', '')} "
+                f"PDF: {'已索引' if ref.get('indexed') else '未下载'}"
+            )
+        return "\n".join(lines)

+ 10 - 0
Co-creation-projects/Lemoween-PaperAssistant/tools/__init__.py

@@ -0,0 +1,10 @@
+from .citation_tool import CitationTool
+from .paper_library_tool import PaperLibrarySearchTool, PaperLibraryAskTool
+from .mcp_paper_search import create_paper_search_mcp_tool
+
+__all__ = [
+    "CitationTool",
+    "PaperLibrarySearchTool",
+    "PaperLibraryAskTool",
+    "create_paper_search_mcp_tool",
+]

+ 86 - 0
Co-creation-projects/Lemoween-PaperAssistant/tools/citation_tool.py

@@ -0,0 +1,86 @@
+"""引用格式化工具(返回 str)"""
+from typing import Any, Dict, List
+
+from hello_agents.tools import Tool, ToolParameter
+
+
+class CitationTool(Tool):
+    """引用格式化工具(GB/T 7714-2015 与 APA 7th)"""
+
+    def __init__(self):
+        super().__init__(
+            name="format_citation",
+            description="将论文元数据格式化为标准引用格式(gb7714 或 apa)。",
+        )
+
+    def get_parameters(self) -> List[ToolParameter]:
+        return [
+            ToolParameter(name="title", type="string",
+                          description="论文标题", required=True),
+            ToolParameter(name="authors", type="string",
+                          description="作者列表,逗号分隔", required=True),
+            ToolParameter(name="year", type="string",
+                          description="年份", required=True),
+            ToolParameter(name="venue", type="string",
+                          description="期刊/会议名", required=False),
+            ToolParameter(name="volume", type="string",
+                          description="卷号", required=False),
+            ToolParameter(name="issue", type="string",
+                          description="期号", required=False),
+            ToolParameter(name="pages", type="string",
+                          description="页码", required=False),
+            ToolParameter(name="doi", type="string",
+                          description="DOI", required=False),
+            ToolParameter(name="style", type="string",
+                          description="gb7714 或 apa", required=False),
+        ]
+
+    def run(self, parameters: Dict[str, Any]) -> str:
+        title = parameters.get("title", "")
+        authors_raw = parameters.get("authors", "")
+        year = parameters.get("year", "")
+        venue = parameters.get("venue", "")
+        volume = parameters.get("volume", "")
+        issue = parameters.get("issue", "")
+        pages = parameters.get("pages", "")
+        doi = parameters.get("doi", "")
+        style = parameters.get("style", "gb7714")
+
+        if not title or not authors_raw:
+            return "❌ title 与 authors 为必填字段"
+
+        author_list = [a.strip() for a in authors_raw.split(",") if a.strip()]
+        authors_str = ", ".join(author_list)
+
+        if style == "gb7714":
+            parts = [f"{authors_str}. {title}[J]."]
+            if venue:
+                parts.append(venue)
+            if year:
+                parts.append(f", {year}")
+            if volume:
+                parts.append(f", {volume}")
+            if issue:
+                parts.append(f"({issue})")
+            if pages:
+                parts.append(f": {pages}")
+            citation = "".join(parts) + "."
+            if doi:
+                citation += f" DOI: {doi}."
+        elif style == "apa":
+            citation = f"{authors_str} ({year}). {title}."
+            if venue:
+                citation += f" {venue}"
+            if volume:
+                citation += f", {volume}"
+            if issue:
+                citation += f"({issue})"
+            if pages:
+                citation += f", {pages}"
+            citation += "."
+            if doi:
+                citation += f" https://doi.org/{doi}"
+        else:
+            citation = f"{authors_str}. {title}. {venue}, {year}."
+
+        return citation

+ 46 - 0
Co-creation-projects/Lemoween-PaperAssistant/tools/mcp_paper_search.py

@@ -0,0 +1,46 @@
+"""Paper Search MCP
+
+把 openags/paper-search-mcp 包装为 HelloAgents 的 MCPTool。
+auto_expand=True 会自动展开为 papersearch_search_papers、
+papersearch_download_with_fallback 等独立工具。
+"""
+import logging
+from typing import List, Optional
+
+from hello_agents.tools import MCPTool
+
+logger = logging.getLogger(__name__)
+
+
+def create_paper_search_mcp_tool(
+    server_command: List[str],
+    prefix: str = "papersearch",
+    env: Optional[dict] = None,
+) -> MCPTool:
+    """创建 Paper Search MCP 工具
+
+    Args:
+        server_command: 启动命令列表,如 ["uvx", "paper-search-mcp"]
+        prefix: 展开后工具的前缀(如 papersearch_search_papers)
+        env: 传给 MCP 子进程的环境变量(API Key 等)
+
+    Returns:
+        已启用 auto_expand 的 MCPTool 实例
+    """
+    if not server_command:
+        raise ValueError("Paper Search MCP 需要提供 server_command")
+
+    logger.info("初始化 Paper Search MCP: %s", server_command)
+
+    return MCPTool(
+        name=prefix,
+        description=(
+            "Paper Search MCP:跨源学术文献检索与全文下载"
+            "(arXiv/PubMed/Semantic Scholar/CrossRef/OpenAlex/dblp 等 20+ 源)。"
+            "主要工具:search_papers(统一检索)、"
+            "download_with_fallback(按 DOI/arXiv ID 下载全文)。"
+        ),
+        server_command=server_command,
+        env=env or {},
+        auto_expand=True,
+    )

+ 82 - 0
Co-creation-projects/Lemoween-PaperAssistant/tools/paper_library_tool.py

@@ -0,0 +1,82 @@
+"""论文库检索/问答工具(包装 RAGTool,返回 str)"""
+from typing import Any, Dict, List
+
+from hello_agents.tools import Tool, ToolParameter
+
+
+class PaperLibrarySearchTool(Tool):
+    """检索已索引的论文库(PDF 原文分块)"""
+
+    def __init__(self, library_service):
+        super().__init__(
+            name="search_paper_library",
+            description=(
+                "在本地论文库中检索与查询最相关的原文片段。"
+                "所有片段来自已下载的学术论文 PDF"
+                "(经 MarkItDown 转换 → 智能分块 → 向量化)。"
+                "撰写章节正文时获取论文细节的主要方式。"
+            ),
+        )
+        self._library = library_service
+
+    def get_parameters(self) -> List[ToolParameter]:
+        return [
+            ToolParameter(name="query", type="string",
+                          description="英文检索查询", required=True),
+            ToolParameter(name="limit", type="integer",
+                          description="返回片段数,默认 5", required=False),
+            ToolParameter(name="use_advanced", type="boolean",
+                          description="是否启用 MQE + HyDE 高级检索",
+                          required=False),
+        ]
+
+    def run(self, parameters: Dict[str, Any]) -> str:
+        query = (parameters.get("query") or "").strip()
+        if not query:
+            return "❌ query 不能为空"
+
+        try:
+            text = self._library.search(
+                query=query,
+                limit=int(parameters.get("limit") or 5),
+                enable_advanced=bool(parameters.get("use_advanced", False)),
+            )
+            return text or "未检索到相关论文片段"
+        except Exception as exc:
+            return f"❌ 论文库检索失败: {exc}"
+
+
+class PaperLibraryAskTool(Tool):
+    """基于论文库直接回答(RAG 增强生成)"""
+
+    def __init__(self, library_service):
+        super().__init__(
+            name="ask_paper_library",
+            description=(
+                "基于已索引论文库直接回答学术问题,"
+                "返回带引用来源的回答。"
+            ),
+        )
+        self._library = library_service
+
+    def get_parameters(self) -> List[ToolParameter]:
+        return [
+            ToolParameter(name="question", type="string",
+                          description="学术问题", required=True),
+            ToolParameter(name="limit", type="integer",
+                          description="检索片段数,默认 5", required=False),
+        ]
+
+    def run(self, parameters: Dict[str, Any]) -> str:
+        question = (parameters.get("question") or "").strip()
+        if not question:
+            return "❌ question 不能为空"
+
+        try:
+            answer = self._library.ask(
+                question=question,
+                limit=int(parameters.get("limit") or 5),
+            )
+            return answer or "未得到回答"
+        except Exception as exc:
+            return f"❌ 论文库问答失败: {exc}"

+ 28 - 0
Co-creation-projects/Lemoween-PaperAssistant/utils.py

@@ -0,0 +1,28 @@
+"""通用工具函数"""
+from __future__ import annotations
+
+import logging
+import re
+
+logger = logging.getLogger(__name__)
+
+
+def strip_thinking_tokens(text: str) -> str:
+    """移除 <think>...</think> 段"""
+    while "<think>" in text and "</think>" in text:
+        start = text.find("<think>")
+        end = text.find("</think>") + len("</think>")
+        text = text[:start] + text[end:]
+    return text
+
+
+def strip_tool_calls(text: str) -> str:
+    """移除残留的 [TOOL_CALL:...] 标记"""
+    if not text:
+        return text
+    return re.sub(r"\[TOOL_CALL:[^\]]+\]", "", text)
+
+
+def normalize_title(title: str) -> str:
+    """标题归一化,用于去重"""
+    return re.sub(r"\s+", " ", (title or "").strip().lower())