v1.2.3 底部快捷问题AI预测:对话进行中由大模型预测用户可能追问的问题(每个≤30字),个数后台可配(默认3,1-6),异步刷新防串扰;初始与开场白一致
This commit is contained in:
@@ -53,6 +53,7 @@ DEFAULT_CONFIG = {
|
|||||||
"footer_text": "NBA球迷大全 · 数据为模拟演示数据(2025-26 赛季) · LLM: DeepSeek · 向量: Chroma + bge-large-zh",
|
"footer_text": "NBA球迷大全 · 数据为模拟演示数据(2025-26 赛季) · LLM: DeepSeek · 向量: Chroma + bge-large-zh",
|
||||||
"admin_password": "admin123",
|
"admin_password": "admin123",
|
||||||
"entity_mark_mode": "first", # 实体标记:first=只标记首次出现 / all=全部标记
|
"entity_mark_mode": "first", # 实体标记:first=只标记首次出现 / all=全部标记
|
||||||
|
"suggestion_count": "3", # 对话中底部快捷问题预测个数(默认3)
|
||||||
}
|
}
|
||||||
|
|
||||||
SEARCHABLE = { # 每个表可搜索的 TEXT 字段
|
SEARCHABLE = { # 每个表可搜索的 TEXT 字段
|
||||||
|
|||||||
@@ -64,6 +64,22 @@ def boot():
|
|||||||
return jsonify(chat.boot_info())
|
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"])
|
@app.route("/api/chat", methods=["POST"])
|
||||||
def api_chat():
|
def api_chat():
|
||||||
|
|||||||
@@ -272,3 +272,53 @@ def boot_info():
|
|||||||
"suggestions": suggest_questions(),
|
"suggestions": suggest_questions(),
|
||||||
"footer_text": cfg.get("footer_text", "NBA球迷大全 · 数据为模拟演示数据(2025-26 赛季)"),
|
"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]
|
||||||
@@ -157,6 +157,10 @@ td.num { text-align:center; }
|
|||||||
<textarea id="cfg-suggestions" style="min-height:160px"></textarea>
|
<textarea id="cfg-suggestions" style="min-height:160px"></textarea>
|
||||||
<div class="tip">💡 一行一个问题。保存后刷新前台页面即可看到新的快捷问题。</div>
|
<div class="tip">💡 一行一个问题。保存后刷新前台页面即可看到新的快捷问题。</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="row2">
|
||||||
|
<div><label>对话中底部快捷问题预测个数(默认3,范围1-6)</label><input type="number" id="cfg-suggestion_count" min="1" max="6">
|
||||||
|
<div class="tip">对话进行中,大模型根据上下文预测用户可能追问的问题数量(每个≤30字)</div></div>
|
||||||
|
</div>
|
||||||
<div class="row2">
|
<div class="row2">
|
||||||
<div><label>管理员密码(留空则不修改)</label><input type="password" id="cfg-admin_password" placeholder="••••••"></div>
|
<div><label>管理员密码(留空则不修改)</label><input type="password" id="cfg-admin_password" placeholder="••••••"></div>
|
||||||
<div><label>实体标记模式</label><select id="cfg-entity_mark_mode">
|
<div><label>实体标记模式</label><select id="cfg-entity_mark_mode">
|
||||||
|
|||||||
@@ -208,6 +208,7 @@ async function loadConfig() {
|
|||||||
$("#cfg-footer_text").value = d.footer_text || "";
|
$("#cfg-footer_text").value = d.footer_text || "";
|
||||||
$("#cfg-admin_password").value = "";
|
$("#cfg-admin_password").value = "";
|
||||||
$("#cfg-entity_mark_mode").value = d.entity_mark_mode === "all" ? "all" : "first";
|
$("#cfg-entity_mark_mode").value = d.entity_mark_mode === "all" ? "all" : "first";
|
||||||
|
$("#cfg-suggestion_count").value = d.suggestion_count || "3";
|
||||||
try { $("#cfg-suggestions").value = JSON.parse(d.suggestions || "[]").join("\n"); }
|
try { $("#cfg-suggestions").value = JSON.parse(d.suggestions || "[]").join("\n"); }
|
||||||
catch (e) { $("#cfg-suggestions").value = ""; }
|
catch (e) { $("#cfg-suggestions").value = ""; }
|
||||||
$("#cfg-msg").textContent = "";
|
$("#cfg-msg").textContent = "";
|
||||||
@@ -224,6 +225,7 @@ $("#cfg-save").addEventListener("click", async () => {
|
|||||||
const pw = $("#cfg-admin_password").value;
|
const pw = $("#cfg-admin_password").value;
|
||||||
if (pw) payload.admin_password = pw;
|
if (pw) payload.admin_password = pw;
|
||||||
payload.entity_mark_mode = $("#cfg-entity_mark_mode").value;
|
payload.entity_mark_mode = $("#cfg-entity_mark_mode").value;
|
||||||
|
payload.suggestion_count = String(Math.min(6, Math.max(1, parseInt($("#cfg-suggestion_count").value || "3"))));
|
||||||
try {
|
try {
|
||||||
await api("/api/admin/config", { method: "PUT", body: JSON.stringify(payload) });
|
await api("/api/admin/config", { method: "PUT", body: JSON.stringify(payload) });
|
||||||
$("#cfg-msg").textContent = "✅ 保存成功,前台刷新后生效";
|
$("#cfg-msg").textContent = "✅ 保存成功,前台刷新后生效";
|
||||||
|
|||||||
@@ -122,6 +122,9 @@ async function sendChat(text) {
|
|||||||
addMsg("bot", html);
|
addMsg("bot", html);
|
||||||
chatHistory.push({ user: text, assistant: d.reply });
|
chatHistory.push({ user: text, assistant: d.reply });
|
||||||
if (chatHistory.length > 20) chatHistory.splice(0, chatHistory.length - 20);
|
if (chatHistory.length > 20) chatHistory.splice(0, chatHistory.length - 20);
|
||||||
|
// 大模型预测下一轮快捷问题(异步刷新底部 chips)
|
||||||
|
const mark = chatHistory.length;
|
||||||
|
refreshChips(mark);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
typing.remove();
|
typing.remove();
|
||||||
addMsg("bot", "⚠️ 网络异常,请稍后再试。");
|
addMsg("bot", "⚠️ 网络异常,请稍后再试。");
|
||||||
@@ -139,6 +142,19 @@ function askQuick(q) {
|
|||||||
sendChat(q);
|
sendChat(q);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 底部快捷问题:对话进行中由大模型预测用户可能追问的问题(异步刷新) */
|
||||||
|
async function refreshChips(mark) {
|
||||||
|
try {
|
||||||
|
const r = await fetch("/api/suggest", { method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ history: chatHistory.slice(-6) }) });
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.suggestions || !d.suggestions.length) return;
|
||||||
|
if (mark !== chatHistory.length) return; // 期间用户又发了新消息 → 丢弃过期预测
|
||||||
|
$("#chips").innerHTML = d.suggestions.map((q) => `<button>${esc(q)}</button>`).join("");
|
||||||
|
$$("#chips button").forEach((b) => b.addEventListener("click", () => askQuick(b.textContent)));
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
/* 聊天区事件委托:快捷语句 / 实体标记 / 新闻链接 / 卡片 */
|
/* 聊天区事件委托:快捷语句 / 实体标记 / 新闻链接 / 卡片 */
|
||||||
$("#chat-list").addEventListener("click", (e) => {
|
$("#chat-list").addEventListener("click", (e) => {
|
||||||
const q = e.target.closest(".quick-q");
|
const q = e.target.closest(".quick-q");
|
||||||
|
|||||||
Reference in New Issue
Block a user