diff --git a/admin.py b/admin.py index d3cb1d7..b23806c 100644 --- a/admin.py +++ b/admin.py @@ -53,6 +53,7 @@ DEFAULT_CONFIG = { "footer_text": "NBA球迷大全 · 数据为模拟演示数据(2025-26 赛季) · LLM: DeepSeek · 向量: Chroma + bge-large-zh", "admin_password": "admin123", "entity_mark_mode": "first", # 实体标记:first=只标记首次出现 / all=全部标记 + "suggestion_count": "3", # 对话中底部快捷问题预测个数(默认3) } SEARCHABLE = { # 每个表可搜索的 TEXT 字段 diff --git a/api.py b/api.py index 03d93f8..761a09d 100644 --- a/api.py +++ b/api.py @@ -64,6 +64,22 @@ def boot(): return jsonify(chat.boot_info()) +@app.route("/api/suggest", methods=["POST"]) +def api_suggest(): + """基于对话历史预测底部快捷问题(个数后台可配,默认3)""" + body = request.get_json(force=True, silent=True) or {} + history = body.get("history") or [] + try: + n = int(admin_mod.get_config().get("suggestion_count", "3") or "3") + except Exception: + n = 3 + try: + return jsonify({"suggestions": chat.predict_suggestions(history, n)}) + except Exception as e: + log.exception("suggest error") + return jsonify({"suggestions": chat.suggest_questions()[:n]}), 200 + + # ------------------------------------------------------------------ 对话 @app.route("/api/chat", methods=["POST"]) def api_chat(): diff --git a/chat.py b/chat.py index e2229a7..09888a0 100644 --- a/chat.py +++ b/chat.py @@ -272,3 +272,53 @@ def boot_info(): "suggestions": suggest_questions(), "footer_text": cfg.get("footer_text", "NBA球迷大全 · 数据为模拟演示数据(2025-26 赛季)"), } + + +def _parse_json_array(text): + """从 LLM 输出中解析 JSON 数组(容错:直接 JSON / 提取中括号段)""" + if not text: + return [] + text = text.strip() + try: + arr = json.loads(text) + if isinstance(arr, list): + return arr + except Exception: + pass + m = re.search(r"\[.*\]", text, re.S) + if m: + try: + arr = json.loads(m.group(0)) + if isinstance(arr, list): + return arr + except Exception: + pass + return [] + + +def predict_suggestions(history=None, n=3): + """基于对话历史,让大模型预测用户接下来最可能追问的 n 个问题(底部快捷语句)。 + 每个问题不超过 30 字;LLM 异常时回退到默认快捷问题。""" + n = max(1, min(int(n or 3), 6)) + history = history or [] + msgs = [{"role": "system", "content": ( + f"你是「NBA球迷大全」智能助手。根据对话历史,站在用户角度预测他接下来最可能追问的{n}个问题。\n" + "要求:\n" + "1. 每个问题不超过30个汉字,简洁口语化\n" + "2. 必须是用户会直接发送的提问,不要编号、不要引号、不要解释\n" + "3. 只输出JSON数组,例如:[\"库里今天拿了几分\",\"湖人下一场什么时候\"],不要输出任何其他内容")}] + for h in history[-6:]: + msgs.append({"role": "user", "content": h.get("user", "")}) + if h.get("assistant"): + msgs.append({"role": "assistant", "content": str(h["assistant"])[:600]}) + if len(msgs) == 1: + return DEFAULT_SUGGESTIONS[:n] + try: + resp = llm.chat(msgs, temperature=0.9, max_tokens=200) + arr = _parse_json_array(llm.parse_content(resp)) + out = [str(x).strip()[:30] for x in arr if str(x).strip()][:n] + if out: + return out + except Exception as e: + log.warning("快捷问题预测失败(%s),回退默认", e) + return DEFAULT_SUGGESTIONS[:n] diff --git a/static/admin.html b/static/admin.html index 1fc47af..f7267cf 100644 --- a/static/admin.html +++ b/static/admin.html @@ -157,6 +157,10 @@ td.num { text-align:center; }