feat: Hydro读题改直连MongoDB(PID双号映射+训练dag解析),不再爬网页
这个提交包含在:
@@ -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: "<h2>说明</h2>..." # 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'<annotation[^>]*>(.*?)</annotation>', r'$\1$', s)
|
||||||
|
s = re.sub(r'<br\s*/?>', '\n', s)
|
||||||
|
s = re.sub(r'</(p|div|h[1-6]|li)>', '\n', s)
|
||||||
|
s = re.sub(r'<li[^>]*>', '- ', 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}
|
||||||
@@ -34,8 +34,8 @@ class Settings(BaseSettings):
|
|||||||
# ---- 多租户账号 ----
|
# ---- 多租户账号 ----
|
||||||
# JWT 签名密钥(生产 .env 必须设置)
|
# JWT 签名密钥(生产 .env 必须设置)
|
||||||
jwt_secret: str = "fluent-learn-dev-secret-change-me"
|
jwt_secret: str = "fluent-learn-dev-secret-change-me"
|
||||||
# Hydro 用户集合 mongodb 直连 URI(建号用;与 Hydro 自身配置一致)
|
# Hydro 用户集合 mongodb 直连 URI(建号/读题用;与 Hydro 自身配置一致)
|
||||||
mongo_uri: str = "mongodb://hydro:change-me@127.0.0.1:27017/hydro"
|
mongo_uri: str = "mongodb://hydro:81bNHD16frqfTMQqTGMFs99rbdNcICDs@127.0.0.1:27017/hydro"
|
||||||
# 新用户默认学科(注册未指定时)
|
# 新用户默认学科(注册未指定时)
|
||||||
default_course: str = "usaco"
|
default_course: str = "usaco"
|
||||||
# 管理员用户名(注册/登录时自动授予 is_admin;逗号分隔)
|
# 管理员用户名(注册/登录时自动授予 is_admin;逗号分隔)
|
||||||
|
|||||||
@@ -1,16 +1,13 @@
|
|||||||
"""Hydro 工具集:暴露给 AI 的 function-calling 工具 schema + 执行器。
|
"""Hydro 工具集:暴露给 AI 的 function-calling 工具 schema + 执行器。
|
||||||
|
|
||||||
设计:
|
数据源:直连 Hydro MongoDB(hydro_db),不依赖网页解析或 API 权限。
|
||||||
- 工具只负责"取数",不做判断;题面截断到 ~4000 字符防止撑爆上下文
|
- 学生说"P57"→ 按显示题号 pid="P57" 查
|
||||||
- 执行器接收 HydroAdapter 实例(复用其登录会话),返回字符串塞回 tool result
|
- 学生说训练名"Scanner"→ 模糊匹配训练 docType=40
|
||||||
- 所有错误转成可读文本返回给 AI,不让 tool call 抛异常中断对话
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import re
|
from app.adapters import hydro_db
|
||||||
|
|
||||||
from app.adapters.hydro_adapter import HydroAdapter
|
|
||||||
|
|
||||||
logger = logging.getLogger("fluent.services.hydro_tools")
|
logger = logging.getLogger("fluent.services.hydro_tools")
|
||||||
|
|
||||||
@@ -19,11 +16,11 @@ TOOLS = [
|
|||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": "hydro_get_problem",
|
"name": "hydro_get_problem",
|
||||||
"description": "按 PID 拉取 Hydro 题面(标题、题目描述、输入输出要求)。学生提到具体题目编号(如 P57、17、113)需要看题时调用;不要凭记忆编造题面。",
|
"description": "按题号拉取 Hydro 题面。学生说 P57、P142、练23.4、或直接给题号时调用;不要凭记忆编造题面。数字会自动匹配显示题号或 Hydro 内部 ID。",
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"pid": {"type": "string", "description": "Hydro 题目 ID,如 57、17、113"}
|
"pid": {"type": "string", "description": "题号,如 P57、57、P142"}
|
||||||
},
|
},
|
||||||
"required": ["pid"],
|
"required": ["pid"],
|
||||||
},
|
},
|
||||||
@@ -33,11 +30,11 @@ TOOLS = [
|
|||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": "hydro_find_training",
|
"name": "hydro_find_training",
|
||||||
"description": "按名称模糊搜索训练/题单(如'Scanner'、'A级'、'循环'、'练23'),返回匹配的训练列表(TID+标题)。学生说'A级训练第几题'或给了训练名称但没给 TID 时,先用这个找 TID。",
|
"description": "按名称模糊搜索训练/题单(如 Scanner、if、循环、A级、for、数组)。学生说'XX训练有哪些题'或'第X题'但没给训练 ID 时,先用这个找训练 ID。",
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"keyword": {"type": "string", "description": "训练名称关键词,如 Scanner、循环、A级、练23"}
|
"keyword": {"type": "string", "description": "训练名称关键词"}
|
||||||
},
|
},
|
||||||
"required": ["keyword"],
|
"required": ["keyword"],
|
||||||
},
|
},
|
||||||
@@ -47,13 +44,13 @@ TOOLS = [
|
|||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": "hydro_list_training",
|
"name": "hydro_list_training",
|
||||||
"description": "列出某个训练(题单)包含的所有题目:PID + 标题。学生说'Scanner 训练有哪些题'或给出 TID 后调用。",
|
"description": "列出某个训练包含的所有题目(按节分组)。先调 hydro_find_training 拿训练 ID,再调这个列题目。",
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"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",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": "hydro_list_my_trainings",
|
"name": "hydro_list_my_trainings",
|
||||||
"description": "列出当前学生可见的所有训练/题单(标题 + TID)。学生问'我有哪些训练'或需要浏览全部训练时调用。",
|
"description": "列出所有训练/题单。学生问'我有哪些训练'或需要浏览时调用。",
|
||||||
"parameters": {"type": "object", "properties": {}},
|
"parameters": {"type": "object", "properties": {}},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def _strip_html(s: str) -> str:
|
async def execute(name: str, args: dict, adapter=None) -> str:
|
||||||
"""Hydro 题面常是 HTML,剥成纯文本/markdown 给 AI。"""
|
|
||||||
s = re.sub(r"<br\s*/?>", "\n", s)
|
|
||||||
s = re.sub(r"</p>", "\n\n", s)
|
|
||||||
s = re.sub(r"<[^>]+>", "", s)
|
|
||||||
return s.strip()
|
|
||||||
|
|
||||||
|
|
||||||
async def execute(name: str, args: dict, adapter: HydroAdapter) -> str:
|
|
||||||
try:
|
try:
|
||||||
if name == "hydro_get_problem":
|
if name == "hydro_get_problem":
|
||||||
pid = str(args.get("pid", "")).lstrip("Pp")
|
pid = str(args.get("pid", "")).strip()
|
||||||
p = await adapter.fetch_problem(pid)
|
p = hydro_db.get_problem(pid)
|
||||||
|
if not p:
|
||||||
|
return f"没找到题号 {pid}。请让学生确认题号,或用 hydro_find_training 按训练名找题。不要编题面。"
|
||||||
content = (p.get("content", "") or "")[:4000]
|
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":
|
if name == "hydro_find_training":
|
||||||
kw = str(args.get("keyword", "")).strip().lower()
|
kw = str(args.get("keyword", "")).strip()
|
||||||
all_t = await adapter.list_my_trainings()
|
matches = hydro_db.find_training(kw)
|
||||||
matches = [t for t in all_t if kw in t["title"].lower()]
|
|
||||||
if not matches:
|
if not matches:
|
||||||
return f"没找到名称含'{kw}'的训练。所有训练:\n" + "\n".join(f"- TID {t['tid']} {t['title']}" for t in all_t[:30])
|
all_t = hydro_db.list_trainings()
|
||||||
rows = "\n".join(f"- TID {t['tid']} {t['title']}" for t in matches[:15])
|
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}"
|
return f"匹配到 {len(matches)} 个训练:\n{rows}"
|
||||||
if name == "hydro_list_training":
|
if name == "hydro_list_training":
|
||||||
t = await adapter.list_training(int(args.get("tid", 0)))
|
tid = str(args.get("training_id", "")).strip()
|
||||||
rows = "\n".join(f"- P{x['pid']} {x['title']}" for x in t.get("problems", []))
|
t = hydro_db.get_training_problems(tid)
|
||||||
return f"训练 {t.get('tid')}:{t.get('title')}\n共 {len(t.get('problems', []))} 题:\n{rows}"
|
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":
|
if name == "hydro_list_my_trainings":
|
||||||
items = await adapter.list_my_trainings()
|
items = hydro_db.list_trainings()
|
||||||
rows = "\n".join(f"- TID {x['tid']} {x['title']}" for x in items[:50])
|
rows = "\n".join(f"- ID {x['id']} {x['title']}" for x in items[:50])
|
||||||
return f"可见训练列表({len(items)} 个):\n{rows}"
|
return f"所有训练({len(items)} 个):\n{rows}"
|
||||||
return f"未知工具:{name}"
|
return f"未知工具:{name}"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("Hydro 工具 %s 失败: %s", name, e)
|
logger.warning("Hydro 工具 %s 失败: %s", name, e)
|
||||||
|
|||||||
在新工单中引用
屏蔽一个用户