From 17ebf03edec55a0f0b56f9c0a7dad6936c13e7f5 Mon Sep 17 00:00:00 2001 From: langxm Date: Wed, 14 Oct 2026 20:58:53 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20Hydro=E8=AF=BB=E9=A2=98=E6=94=B9?= =?UTF-8?q?=E7=9B=B4=E8=BF=9EMongoDB(PID=E5=8F=8C=E5=8F=B7=E6=98=A0?= =?UTF-8?q?=E5=B0=84+=E8=AE=AD=E7=BB=83dag=E8=A7=A3=E6=9E=90)=EF=BC=8C?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E7=88=AC=E7=BD=91=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/adapters/hydro_db.py | 112 ++++++++++++++++++++++++++++ backend/app/core/config.py | 4 +- backend/app/services/hydro_tools.py | 74 +++++++++--------- 3 files changed, 150 insertions(+), 40 deletions(-) create mode 100644 backend/app/adapters/hydro_db.py diff --git a/backend/app/adapters/hydro_db.py b/backend/app/adapters/hydro_db.py new file mode 100644 index 0000000..b3dfc0a --- /dev/null +++ b/backend/app/adapters/hydro_db.py @@ -0,0 +1,112 @@ +"""Hydro MongoDB 直连读题/读训练(不依赖网页解析或 API 权限)。 + +文档集合 schema(docType=10 题目): + _id: ObjectId + pid: "P57" # 学生说的显示题号 + reference.pid: 442 # URL /p/442 用的数字 ID + title: "练11.4..." + content.zh: "

说明

..." # HTML 题面 + tag: [...] + +训练(docType=40): + title: "1 Scanner 训练" + dag: [{"title": "...", "pids": [17, 7, 9, ...]}] # pids 是 reference.pid 数字 +""" +from __future__ import annotations +import logging, re, json +from typing import Any +import pymongo +from app.core.config import settings + +logger = logging.getLogger("fluent.hydro_db") + +_client: pymongo.MongoClient | None = None +_db = None + + +def _get_db(): + global _client, _db + if _db is None: + _client = pymongo.MongoClient(settings.mongo_uri, serverSelectionTimeoutMS=3000) + _db = _client.get_database() + return _db + + +def _strip_html(s: str) -> str: + s = re.sub(r']*>(.*?)', r'$\1$', s) + s = re.sub(r'', '\n', s) + s = re.sub(r'', '\n', s) + s = re.sub(r']*>', '- ', s) + s = re.sub(r'<[^>]+>', '', s) + return re.sub(r'\n{3,}', '\n\n', s).strip() + + +def _parse_content(raw) -> str: + """content 可能是 dict 或 JSON 字符串,取 zh 字段再剥 HTML。""" + if isinstance(raw, str): + try: + raw = json.loads(raw) + except Exception: + return _strip_html(raw) + if isinstance(raw, dict): + raw = raw.get("zh") or raw.get("en") or "" + return _strip_html(str(raw)) + + +def get_problem(pid_input: str) -> dict | None: + """按显示题号(P57)或数字 ID(442)查题目。""" + db = _get_db() + q: dict[str, Any] = {"docType": 10} + pid = pid_input.strip().upper().lstrip("P") + if pid.isdigit(): + q["$or"] = [ + {"pid": f"P{pid}"}, + {"sort": f"P{pid.zfill(6)}"}, + {"reference.pid": int(pid)}, + ] + else: + q["pid"] = f"P{pid}" + doc = db.document.find_one(q) + if not doc: + return None + ref = doc.get("reference") or {} + return { + "pid": doc.get("pid", ""), + "title": doc.get("title", ""), + "numeric_id": ref.get("pid", 0), + "content": _parse_content(doc.get("content")), + } + + +def list_trainings() -> list[dict]: + db = _get_db() + out = [] + for t in db.document.find({"docType": 40}, {"title": 1, "description": 1, "domainId": 1}): + out.append({"id": str(t["_id"]), "title": t.get("title", ""), "domainId": t.get("domainId", "")}) + return out + + +def find_training(keyword: str) -> list[dict]: + kw = keyword.strip().lower() + return [t for t in list_trainings() if kw in t["title"].lower()] + + +def get_training_problems(training_id: str) -> dict: + from bson import ObjectId + db = _get_db() + doc = db.document.find_one({"_id": ObjectId(training_id), "docType": 40}) + if not doc: + return {} + domain = doc.get("domainId", "") + sections = [] + for sec in doc.get("dag") or []: + probs = [] + for did in sec.get("pids") or []: + p = db.document.find_one( + {"docType": 10, "docId": did, "domainId": domain}, + {"pid": 1, "title": 1}, + ) + if p: + probs.append({"pid": p.get("pid", ""), "title": p.get("title", "")}) + sections.append({"title": sec.get("title", ""), "problems": probs}) + return {"title": doc.get("title", ""), "sections": sections} diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 8bd89bd..73c1261 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -34,8 +34,8 @@ class Settings(BaseSettings): # ---- 多租户账号 ---- # JWT 签名密钥(生产 .env 必须设置) jwt_secret: str = "fluent-learn-dev-secret-change-me" - # Hydro 用户集合 mongodb 直连 URI(建号用;与 Hydro 自身配置一致) - mongo_uri: str = "mongodb://hydro:change-me@127.0.0.1:27017/hydro" + # Hydro 用户集合 mongodb 直连 URI(建号/读题用;与 Hydro 自身配置一致) + mongo_uri: str = "mongodb://hydro:81bNHD16frqfTMQqTGMFs99rbdNcICDs@127.0.0.1:27017/hydro" # 新用户默认学科(注册未指定时) default_course: str = "usaco" # 管理员用户名(注册/登录时自动授予 is_admin;逗号分隔) diff --git a/backend/app/services/hydro_tools.py b/backend/app/services/hydro_tools.py index d1bc912..d537825 100644 --- a/backend/app/services/hydro_tools.py +++ b/backend/app/services/hydro_tools.py @@ -1,16 +1,13 @@ """Hydro 工具集:暴露给 AI 的 function-calling 工具 schema + 执行器。 -设计: -- 工具只负责"取数",不做判断;题面截断到 ~4000 字符防止撑爆上下文 -- 执行器接收 HydroAdapter 实例(复用其登录会话),返回字符串塞回 tool result -- 所有错误转成可读文本返回给 AI,不让 tool call 抛异常中断对话 +数据源:直连 Hydro MongoDB(hydro_db),不依赖网页解析或 API 权限。 +- 学生说"P57"→ 按显示题号 pid="P57" 查 +- 学生说训练名"Scanner"→ 模糊匹配训练 docType=40 """ from __future__ import annotations import logging -import re - -from app.adapters.hydro_adapter import HydroAdapter +from app.adapters import hydro_db logger = logging.getLogger("fluent.services.hydro_tools") @@ -19,11 +16,11 @@ TOOLS = [ "type": "function", "function": { "name": "hydro_get_problem", - "description": "按 PID 拉取 Hydro 题面(标题、题目描述、输入输出要求)。学生提到具体题目编号(如 P57、17、113)需要看题时调用;不要凭记忆编造题面。", + "description": "按题号拉取 Hydro 题面。学生说 P57、P142、练23.4、或直接给题号时调用;不要凭记忆编造题面。数字会自动匹配显示题号或 Hydro 内部 ID。", "parameters": { "type": "object", "properties": { - "pid": {"type": "string", "description": "Hydro 题目 ID,如 57、17、113"} + "pid": {"type": "string", "description": "题号,如 P57、57、P142"} }, "required": ["pid"], }, @@ -33,11 +30,11 @@ TOOLS = [ "type": "function", "function": { "name": "hydro_find_training", - "description": "按名称模糊搜索训练/题单(如'Scanner'、'A级'、'循环'、'练23'),返回匹配的训练列表(TID+标题)。学生说'A级训练第几题'或给了训练名称但没给 TID 时,先用这个找 TID。", + "description": "按名称模糊搜索训练/题单(如 Scanner、if、循环、A级、for、数组)。学生说'XX训练有哪些题'或'第X题'但没给训练 ID 时,先用这个找训练 ID。", "parameters": { "type": "object", "properties": { - "keyword": {"type": "string", "description": "训练名称关键词,如 Scanner、循环、A级、练23"} + "keyword": {"type": "string", "description": "训练名称关键词"} }, "required": ["keyword"], }, @@ -47,13 +44,13 @@ TOOLS = [ "type": "function", "function": { "name": "hydro_list_training", - "description": "列出某个训练(题单)包含的所有题目:PID + 标题。学生说'Scanner 训练有哪些题'或给出 TID 后调用。", + "description": "列出某个训练包含的所有题目(按节分组)。先调 hydro_find_training 拿训练 ID,再调这个列题目。", "parameters": { "type": "object", "properties": { - "tid": {"type": "integer", "description": "训练 ID(先调 hydro_find_training 用名称找 TID)"} + "training_id": {"type": "string", "description": "训练 ID(来自 hydro_find_training 结果)"} }, - "required": ["tid"], + "required": ["training_id"], }, }, }, @@ -61,44 +58,45 @@ TOOLS = [ "type": "function", "function": { "name": "hydro_list_my_trainings", - "description": "列出当前学生可见的所有训练/题单(标题 + TID)。学生问'我有哪些训练'或需要浏览全部训练时调用。", + "description": "列出所有训练/题单。学生问'我有哪些训练'或需要浏览时调用。", "parameters": {"type": "object", "properties": {}}, }, }, ] -def _strip_html(s: str) -> str: - """Hydro 题面常是 HTML,剥成纯文本/markdown 给 AI。""" - s = re.sub(r"", "\n", s) - s = re.sub(r"

", "\n\n", s) - s = re.sub(r"<[^>]+>", "", s) - return s.strip() - - -async def execute(name: str, args: dict, adapter: HydroAdapter) -> str: +async def execute(name: str, args: dict, adapter=None) -> str: try: if name == "hydro_get_problem": - pid = str(args.get("pid", "")).lstrip("Pp") - p = await adapter.fetch_problem(pid) + pid = str(args.get("pid", "")).strip() + p = hydro_db.get_problem(pid) + if not p: + return f"没找到题号 {pid}。请让学生确认题号,或用 hydro_find_training 按训练名找题。不要编题面。" content = (p.get("content", "") or "")[:4000] - return f"题目 P{p.get('pid')}:{p.get('title')}\n\n题面:\n{content}" + return f"题目 {p['pid']}:{p['title']}\n\n题面:\n{content}" if name == "hydro_find_training": - kw = str(args.get("keyword", "")).strip().lower() - all_t = await adapter.list_my_trainings() - matches = [t for t in all_t if kw in t["title"].lower()] + kw = str(args.get("keyword", "")).strip() + matches = hydro_db.find_training(kw) if not matches: - return f"没找到名称含'{kw}'的训练。所有训练:\n" + "\n".join(f"- TID {t['tid']} {t['title']}" for t in all_t[:30]) - rows = "\n".join(f"- TID {t['tid']} {t['title']}" for t in matches[:15]) + all_t = hydro_db.list_trainings() + return f"没找到名称含'{kw}'的训练。所有训练:\n" + "\n".join(f"- ID {t['id']} {t['title']}" for t in all_t[:30]) + rows = "\n".join(f"- ID {t['id']} {t['title']}" for t in matches[:15]) return f"匹配到 {len(matches)} 个训练:\n{rows}" if name == "hydro_list_training": - t = await adapter.list_training(int(args.get("tid", 0))) - rows = "\n".join(f"- P{x['pid']} {x['title']}" for x in t.get("problems", [])) - return f"训练 {t.get('tid')}:{t.get('title')}\n共 {len(t.get('problems', []))} 题:\n{rows}" + tid = str(args.get("training_id", "")).strip() + t = hydro_db.get_training_problems(tid) + if not t: + return f"没找到训练 {tid}。" + lines = [f"训练:{t['title']}"] + for sec in t.get("sections", []): + lines.append(f"\n【{sec['title']}】") + for x in sec.get("problems", []): + lines.append(f" {x['pid']} {x['title']}") + return "\n".join(lines) if name == "hydro_list_my_trainings": - items = await adapter.list_my_trainings() - rows = "\n".join(f"- TID {x['tid']} {x['title']}" for x in items[:50]) - return f"可见训练列表({len(items)} 个):\n{rows}" + items = hydro_db.list_trainings() + rows = "\n".join(f"- ID {x['id']} {x['title']}" for x in items[:50]) + return f"所有训练({len(items)} 个):\n{rows}" return f"未知工具:{name}" except Exception as e: logger.warning("Hydro 工具 %s 失败: %s", name, e)