Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bac19202b7 | ||
|
|
8b7ab976d8 | ||
|
|
0a3b075644 | ||
|
|
437e707893 | ||
|
|
0ff0aff87b | ||
|
|
c03d6c3fe2 | ||
|
|
a122a498e1 |
@@ -52,6 +52,8 @@ DEFAULT_CONFIG = {
|
||||
], ensure_ascii=False),
|
||||
"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 字段
|
||||
@@ -189,7 +191,15 @@ def list_rows(table):
|
||||
page = max(1, int(request.args.get("page", 1)))
|
||||
size = min(100, max(1, int(request.args.get("size", 20))))
|
||||
q = (request.args.get("q") or "").strip()
|
||||
# 排序:字段白名单校验(防注入),默认 id 降序
|
||||
cols = _columns(table)
|
||||
valid_fields = {c["name"] for c in cols}
|
||||
sort = request.args.get("sort", "") or "id"
|
||||
if sort not in valid_fields:
|
||||
sort = "id"
|
||||
order = (request.args.get("order", "") or "desc").lower()
|
||||
if order not in ("asc", "desc"):
|
||||
order = "desc"
|
||||
where, args = "", []
|
||||
if q:
|
||||
fields = SEARCHABLE.get(table) or ()
|
||||
@@ -198,10 +208,11 @@ def list_rows(table):
|
||||
where = "WHERE " + " OR ".join(f"{f} LIKE ? ESCAPE '\\'" for f in fields)
|
||||
args = [like] * len(fields)
|
||||
total = query_one(f"SELECT COUNT(*) AS c FROM {table} {where}", args)["c"]
|
||||
rows = query(f"SELECT * FROM {table} {where} ORDER BY id DESC LIMIT ? OFFSET ?",
|
||||
rows = query(f"SELECT * FROM {table} {where} ORDER BY {sort} {order.upper()}, id {order.upper()} LIMIT ? OFFSET ?",
|
||||
args + [size, (page - 1) * size])
|
||||
return jsonify({"table": table, "cn": TABLES[table], "columns": cols,
|
||||
"total": total, "page": page, "size": size, "rows": rows})
|
||||
"total": total, "page": page, "size": size, "rows": rows,
|
||||
"sort": sort, "order": order})
|
||||
|
||||
|
||||
def get_row(table, rid):
|
||||
|
||||
@@ -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():
|
||||
@@ -78,7 +94,8 @@ def api_chat():
|
||||
game_refs = [it for s in sources
|
||||
if s.get("tool") in ("search_games", "get_game_detail")
|
||||
for it in s.get("items", [])]
|
||||
spans, cards = entity_linker.link_entities(reply, game_refs=game_refs)
|
||||
mark_mode = admin_mod.get_config().get("entity_mark_mode", "first")
|
||||
spans, cards = entity_linker.link_entities(reply, game_refs=game_refs, mark_mode=mark_mode)
|
||||
return jsonify({"reply": reply, "sources": sources, "used_tools": used_tools,
|
||||
"news_refs": news_refs, "entities": spans, "cards": cards})
|
||||
except Exception as e:
|
||||
|
||||
@@ -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]
|
||||
+11
-1
@@ -164,13 +164,23 @@ def _match_games(text, game_refs):
|
||||
return cards
|
||||
|
||||
|
||||
def link_entities(text, game_refs=None):
|
||||
def link_entities(text, game_refs=None, mark_mode="first"):
|
||||
"""主入口:扫描回答文本。
|
||||
返回 (spans, cards)
|
||||
spans: 实体命中区间(前端高亮标记用),按 start 升序、互不重叠
|
||||
mark_mode="first" 时同一实体(type,id)只保留首次出现;"all" 时全部标记
|
||||
cards: 快速查看卡片数据(每类限量,避免刷屏)
|
||||
"""
|
||||
spans = _find_spans(text or "")
|
||||
if mark_mode == "first":
|
||||
seen, kept = set(), []
|
||||
for sp in spans: # spans 已按 start 升序 → 保留首次
|
||||
key = (sp["type"], sp["id"])
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
kept.append(sp)
|
||||
spans = kept
|
||||
cards = []
|
||||
seen_cards = set()
|
||||
for sp in spans:
|
||||
|
||||
@@ -46,6 +46,9 @@ body { background:var(--bg); color:var(--txt); font-family:"PingFang SC","Micros
|
||||
table { width:100%; border-collapse:collapse; }
|
||||
th, td { padding:9px 11px; text-align:left; font-size:13px; border-bottom:1px solid var(--line); white-space:nowrap; max-width:260px; overflow:hidden; text-overflow:ellipsis; }
|
||||
th { background:var(--bg2); color:var(--sub); font-weight:600; font-size:12px; position:sticky; top:0; }
|
||||
th.sortable { cursor:pointer; user-select:none; transition:.15s; }
|
||||
th.sortable:hover { color:var(--orange2); }
|
||||
th.sort-active { color:var(--orange2); }
|
||||
tr:hover td { background:rgba(249,115,22,.05); }
|
||||
td.num { text-align:center; }
|
||||
.row-ops { display:flex; gap:6px; }
|
||||
@@ -157,8 +160,17 @@ td.num { text-align:center; }
|
||||
<textarea id="cfg-suggestions" style="min-height:160px"></textarea>
|
||||
<div class="tip">💡 一行一个问题。保存后刷新前台页面即可看到新的快捷问题。</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><label>管理员密码(留空则不修改)</label><input type="password" id="cfg-admin_password" placeholder="••••••"></div>
|
||||
<div><label>实体标记模式</label><select id="cfg-entity_mark_mode">
|
||||
<option value="first">只标记首次出现(推荐)</option>
|
||||
<option value="all">全部标记</option>
|
||||
</select>
|
||||
<div class="tip">对话回答中球队/球员/人物等特殊标记策略</div></div>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button class="btn" id="cfg-save">💾 保存配置</button>
|
||||
|
||||
+24
-5
@@ -4,7 +4,7 @@ const $$ = (s) => [...document.querySelectorAll(s)];
|
||||
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||||
|
||||
let TOKEN = localStorage.getItem("nba_admin_token") || "";
|
||||
let CUR = { table: "", page: 1, q: "" };
|
||||
let CUR = { table: "", page: 1, q: "", sort: "id", order: "desc" };
|
||||
let LOOKUPS = {}; // teams/players/leagues/sports → {id: name}
|
||||
|
||||
/* 字段中文名 */
|
||||
@@ -79,7 +79,7 @@ function switchPage(p) {
|
||||
$("#page-config").classList.toggle("hidden", p !== "config");
|
||||
if (p === "stats") loadStats();
|
||||
else if (p === "config") loadConfig();
|
||||
else { CUR = { table: p, page: 1, q: "" }; $("#tbl-search").value = ""; loadTable(); }
|
||||
else { CUR = { table: p, page: 1, q: "", sort: "id", order: "desc" }; $("#tbl-search").value = ""; loadTable(); }
|
||||
}
|
||||
|
||||
/* ================= 仪表盘 ================= */
|
||||
@@ -108,16 +108,20 @@ async function loadLookups() {
|
||||
|
||||
async function loadTable() {
|
||||
$("#table-title").textContent = TITLE_CN[CUR.table] || CUR.table;
|
||||
const d = await api(`/api/admin/${CUR.table}?page=${CUR.page}&size=20&q=${encodeURIComponent(CUR.q)}`);
|
||||
const d = await api(`/api/admin/${CUR.table}?page=${CUR.page}&size=20&q=${encodeURIComponent(CUR.q)}&sort=${encodeURIComponent(CUR.sort)}&order=${CUR.order}`);
|
||||
const cols = d.columns.filter((c) => c.name !== "created_at");
|
||||
const rows = d.rows;
|
||||
if (!Object.keys(LOOKUPS).length) await loadLookups().catch(() => {});
|
||||
const thead = `<tr>${cols.map((c) => `<th>${esc(FIELD_CN[CUR.table]?.[c.name] || c.name)}</th>`).join("")}<th>操作</th></tr>`;
|
||||
const thead = `<tr>${cols.map((c) => {
|
||||
const active = CUR.sort === c.name;
|
||||
const arrow = active ? (CUR.order === "asc" ? " ▲" : " ▼") : "";
|
||||
return `<th class="sortable ${active ? "sort-active" : ""}" data-sort="${c.name}" title="点击排序">${esc(FIELD_CN[CUR.table]?.[c.name] || c.name)}${arrow}</th>`;
|
||||
}).join("")}<th>操作</th></tr>`;
|
||||
const tbody = rows.map((r) => {
|
||||
const tds = cols.map((c) => {
|
||||
let v = r[c.name];
|
||||
if (v === null || v === undefined) v = "";
|
||||
if (c.name === "id") v = `<span class="badge">#${v}</span>`;
|
||||
if (c.name === "id") v = v; // ID 列纯数值显示
|
||||
else if (["team_id", "home_team_id", "away_team_id"].includes(c.name)) v = (LOOKUPS.teams || {})[v] || v;
|
||||
else if (c.name === "player_id") v = (LOOKUPS.players || {})[v] || v;
|
||||
else if (c.name === "league_id") v = (LOOKUPS.leagues || {})[v] || v;
|
||||
@@ -141,6 +145,17 @@ $("#tbl-search-btn").addEventListener("click", () => { CUR.q = $("#tbl-search").
|
||||
$("#tbl-search").addEventListener("keydown", (e) => { if (e.key === "Enter") $("#tbl-search-btn").click(); });
|
||||
$("#tbl-add").addEventListener("click", () => openEdit(CUR.table, null));
|
||||
|
||||
/* 表头点击排序:首次点击升序,再点切降序,循环 */
|
||||
$("#tbl-wrap").addEventListener("click", (e) => {
|
||||
const th = e.target.closest("th[data-sort]");
|
||||
if (!th) return;
|
||||
const f = th.dataset.sort;
|
||||
if (CUR.sort === f) CUR.order = CUR.order === "asc" ? "desc" : "asc";
|
||||
else { CUR.sort = f; CUR.order = "asc"; }
|
||||
CUR.page = 1;
|
||||
loadTable();
|
||||
});
|
||||
|
||||
/* ================= 编辑弹窗 ================= */
|
||||
let EDIT = { table: "", id: null };
|
||||
|
||||
@@ -207,6 +222,8 @@ async function loadConfig() {
|
||||
$("#cfg-welcome_hint").value = d.welcome_hint || "";
|
||||
$("#cfg-footer_text").value = d.footer_text || "";
|
||||
$("#cfg-admin_password").value = "";
|
||||
$("#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"); }
|
||||
catch (e) { $("#cfg-suggestions").value = ""; }
|
||||
$("#cfg-msg").textContent = "";
|
||||
@@ -222,6 +239,8 @@ $("#cfg-save").addEventListener("click", async () => {
|
||||
};
|
||||
const pw = $("#cfg-admin_password").value;
|
||||
if (pw) payload.admin_password = pw;
|
||||
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 {
|
||||
await api("/api/admin/config", { method: "PUT", body: JSON.stringify(payload) });
|
||||
$("#cfg-msg").textContent = "✅ 保存成功,前台刷新后生效";
|
||||
|
||||
+183
-25
@@ -6,6 +6,36 @@ const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "
|
||||
const chatHistory = [];
|
||||
let chatBusy = false;
|
||||
|
||||
/* 简洁版当前时间 HH:MM */
|
||||
function nowTime() {
|
||||
const d = new Date();
|
||||
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/* 轻提示 */
|
||||
function toast(msg) {
|
||||
let t = document.getElementById("toast");
|
||||
if (!t) { t = document.createElement("div"); t.id = "toast"; document.body.appendChild(t); }
|
||||
t.textContent = msg;
|
||||
t.classList.add("show");
|
||||
clearTimeout(t._timer);
|
||||
t._timer = setTimeout(() => t.classList.remove("show"), 1800);
|
||||
}
|
||||
|
||||
/* 复制文本(Clipboard API + 降级) */
|
||||
async function copyText(text) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch (e) {
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0";
|
||||
document.body.appendChild(ta); ta.select();
|
||||
document.execCommand("copy");
|
||||
ta.remove();
|
||||
}
|
||||
toast("✅ 已复制");
|
||||
}
|
||||
|
||||
/* ================= Markdown 渲染(marked 本地库,先转义防 XSS) ================= */
|
||||
function md(text) {
|
||||
if (window.marked) {
|
||||
@@ -61,10 +91,14 @@ function loadView(v) {
|
||||
}
|
||||
|
||||
/* ================= 对话 ================= */
|
||||
function addMsg(role, html) {
|
||||
function addMsg(role, html, opts = {}) {
|
||||
const div = document.createElement("div");
|
||||
div.className = `msg ${role}`;
|
||||
div.innerHTML = `<div class="avatar">${role === "user" ? "🧑" : "🤖"}</div><div class="bubble">${html}</div>`;
|
||||
if (opts.idx !== undefined) div.dataset.idx = opts.idx;
|
||||
const actions = role === "bot"
|
||||
? `<div class="msg-actions"><button class="act-btn" title="复制回答">📋</button><button class="act-btn" title="重新生成">🔄</button><span class="msg-time">${nowTime()}</span></div>`
|
||||
: `<div class="msg-actions user-time"><span class="msg-time">${nowTime()}</span></div>`;
|
||||
div.innerHTML = `<div class="avatar">${role === "user" ? "🧑" : "🤖"}</div><div class="msg-body"><div class="bubble">${html}</div>${actions}</div>`;
|
||||
$("#chat-list").appendChild(div);
|
||||
$("#chat-list").scrollTop = $("#chat-list").scrollHeight;
|
||||
return div;
|
||||
@@ -72,7 +106,7 @@ function addMsg(role, html) {
|
||||
function showTyping() {
|
||||
const div = document.createElement("div");
|
||||
div.className = "msg bot";
|
||||
div.innerHTML = `<div class="avatar">🤖</div><div class="bubble"><span class="typing"><i></i><i></i><i></i></span></div>`;
|
||||
div.innerHTML = `<div class="avatar">🤖</div><div class="msg-body"><div class="bubble"><span class="typing"><i></i><i></i><i></i></span></div></div>`;
|
||||
$("#chat-list").appendChild(div);
|
||||
$("#chat-list").scrollTop = $("#chat-list").scrollHeight;
|
||||
return div;
|
||||
@@ -90,6 +124,28 @@ function cardHtml(c) {
|
||||
return "";
|
||||
}
|
||||
|
||||
/* 组装回答气泡 HTML(参考资讯 + markdown实体 + 卡片 + 来源) */
|
||||
function buildBotHtml(d) {
|
||||
let html = "";
|
||||
// 需求4:参考资讯(新闻/百科链接),默认折叠,位于回答块上方
|
||||
if (d.news_refs && d.news_refs.length) {
|
||||
html += `<details class="refs"><summary>📰 参考资讯(${d.news_refs.length})</summary><ul>` +
|
||||
d.news_refs.map((n) => `<li><a href="#" data-news="${n.id}">${esc(n.title)}</a>` +
|
||||
(n.source ? `<span class="ref-src">${esc(n.source)}${n.publish_time ? " · " + esc(n.publish_time.slice(0, 10)) : ""}</span>` : "") + `</li>`).join("") +
|
||||
`</ul></details>`;
|
||||
}
|
||||
// 需求3:markdown 渲染 + 需求5:实体特殊标记
|
||||
html += `<div class="md">${renderMdWithEntities(d.reply, d.entities)}</div>`;
|
||||
// 需求5:快速查看入口卡片
|
||||
if (d.cards && d.cards.length) {
|
||||
html += `<div class="entity-cards">${d.cards.map(cardHtml).join("")}</div>`;
|
||||
}
|
||||
if (d.sources && d.sources.length) {
|
||||
html += "<div class='src-line'>" + d.sources.map((s) => `<span class="src-tag">来源:${esc(s.tool)}</span>`).join("") + "</div>";
|
||||
}
|
||||
return html;
|
||||
}
|
||||
|
||||
async function sendChat(text) {
|
||||
if (chatBusy) return;
|
||||
chatBusy = true;
|
||||
@@ -102,26 +158,21 @@ async function sendChat(text) {
|
||||
const d = await r.json();
|
||||
typing.remove();
|
||||
if (d.error) { addMsg("bot", `⚠️ ${esc(d.error)}`); return; }
|
||||
let html = "";
|
||||
// 需求4:参考资讯(新闻/百科链接),默认折叠,位于回答块上方
|
||||
if (d.news_refs && d.news_refs.length) {
|
||||
html += `<details class="refs"><summary>📰 参考资讯(${d.news_refs.length})</summary><ul>` +
|
||||
d.news_refs.map((n) => `<li><a href="#" data-news="${n.id}">${esc(n.title)}</a>` +
|
||||
(n.source ? `<span class="ref-src">${esc(n.source)}${n.publish_time ? " · " + esc(n.publish_time.slice(0, 10)) : ""}</span>` : "") + `</li>`).join("") +
|
||||
`</ul></details>`;
|
||||
}
|
||||
// 需求3:markdown 渲染 + 需求5:实体特殊标记
|
||||
html += `<div class="md">${renderMdWithEntities(d.reply, d.entities)}</div>`;
|
||||
// 需求5:快速查看入口卡片
|
||||
if (d.cards && d.cards.length) {
|
||||
html += `<div class="entity-cards">${d.cards.map(cardHtml).join("")}</div>`;
|
||||
}
|
||||
if (d.sources && d.sources.length) {
|
||||
html += "<div class='src-line'>" + d.sources.map((s) => `<span class="src-tag">来源:${esc(s.tool)}</span>`).join("") + "</div>";
|
||||
}
|
||||
addMsg("bot", html);
|
||||
chatHistory.push({ user: text, assistant: d.reply });
|
||||
if (chatHistory.length > 20) chatHistory.splice(0, chatHistory.length - 20);
|
||||
const idx = chatHistory.length - 1;
|
||||
addMsg("bot", buildBotHtml(d), { idx });
|
||||
if (chatHistory.length > 20) {
|
||||
const removed = chatHistory.length - 20;
|
||||
chatHistory.splice(0, removed);
|
||||
document.querySelectorAll("#chat-list .msg[data-idx]").forEach((m) => {
|
||||
const i = parseInt(m.dataset.idx);
|
||||
if (i < removed) m.remove();
|
||||
else m.dataset.idx = i - removed;
|
||||
});
|
||||
}
|
||||
// 大模型预测下一轮快捷问题(异步刷新底部 chips)
|
||||
const mark = chatHistory.length;
|
||||
refreshChips(mark);
|
||||
} catch (e) {
|
||||
typing.remove();
|
||||
addMsg("bot", "⚠️ 网络异常,请稍后再试。");
|
||||
@@ -130,17 +181,124 @@ async function sendChat(text) {
|
||||
$("#send-btn").disabled = false;
|
||||
}
|
||||
}
|
||||
$("#send-btn").addEventListener("click", () => { const v = $("#chat-input").value.trim(); if (v) { $("#chat-input").value = ""; sendChat(v); } });
|
||||
$("#chat-input").addEventListener("keydown", (e) => { if (e.key === "Enter") $("#send-btn").click(); });
|
||||
$("#send-btn").addEventListener("click", () => { const v = $("#chat-input").value.trim(); if (v) { $("#chat-input").value = ""; autoResizeInput(); sendChat(v); } });
|
||||
|
||||
/* 输入框多行自适应:超一行自动增高,最多 4 行(约90px);Enter 发送,Shift+Enter 换行 */
|
||||
const chatInput = $("#chat-input");
|
||||
const INPUT_MAX_H = 90;
|
||||
function autoResizeInput() {
|
||||
chatInput.style.height = "auto";
|
||||
chatInput.style.height = Math.min(chatInput.scrollHeight, INPUT_MAX_H) + "px";
|
||||
}
|
||||
chatInput.addEventListener("input", autoResizeInput);
|
||||
chatInput.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
$("#send-btn").click();
|
||||
}
|
||||
});
|
||||
|
||||
/* 复制当前回答(纯文本) */
|
||||
function copyMsg(btn) {
|
||||
const bubble = btn.closest(".msg").querySelector(".bubble");
|
||||
copyText(bubble.innerText.trim());
|
||||
}
|
||||
|
||||
/* 重新生成:以该轮之前的上下文重新提问,替换本条回答,截断后续对话 */
|
||||
async function regenerate(btn) {
|
||||
const msgEl = btn.closest(".msg");
|
||||
const idx = parseInt(msgEl.dataset.idx);
|
||||
if (isNaN(idx) || chatBusy) return;
|
||||
if (idx >= chatHistory.length) return;
|
||||
// 截断:删除该条之后的对话(上下文已变)
|
||||
chatHistory.splice(idx + 1);
|
||||
document.querySelectorAll("#chat-list .msg[data-idx]").forEach((m) => {
|
||||
if (parseInt(m.dataset.idx) > idx) m.remove();
|
||||
});
|
||||
const userText = chatHistory[idx].user;
|
||||
const body = msgEl.querySelector(".msg-body");
|
||||
const bubble = msgEl.querySelector(".bubble");
|
||||
bubble.innerHTML = `<span class="typing"><i></i><i></i><i></i></span>`;
|
||||
msgEl.querySelector(".msg-actions")?.remove();
|
||||
chatBusy = true;
|
||||
try {
|
||||
const r = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ message: userText, history: chatHistory.slice(0, idx).map((h) => ({ user: h.user, assistant: h.assistant })) }) });
|
||||
const d = await r.json();
|
||||
if (d.error) { bubble.innerHTML = `⚠️ ${esc(d.error)}`; return; }
|
||||
bubble.innerHTML = buildBotHtml(d);
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "msg-actions";
|
||||
actions.innerHTML = `<button class="act-btn" title="复制回答">📋</button><button class="act-btn" title="重新生成">🔄</button><span class="msg-time">${nowTime()}</span>`;
|
||||
body.appendChild(actions);
|
||||
chatHistory[idx] = { user: userText, assistant: d.reply };
|
||||
refreshChips(chatHistory.length);
|
||||
} catch (e) {
|
||||
bubble.innerHTML = "⚠️ 网络异常,请稍后再试。";
|
||||
} finally {
|
||||
chatBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* 分享:弹窗展示对话全文 + 一键复制 */
|
||||
function shareChat() {
|
||||
if (!chatHistory.length) { toast("还没有对话内容"); return; }
|
||||
const text = chatHistory.map((h) => `🧑 ${h.user}\n🤖 ${h.assistant}`).join("\n\n");
|
||||
openModal(`
|
||||
<h2>🔗 分享对话</h2>
|
||||
<div class="en">共 ${chatHistory.length} 轮 · 复制后粘贴到任意聊天或文档</div>
|
||||
<textarea readonly class="share-box" style="width:100%;height:280px;margin-top:10px;background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:12px;color:var(--txt);font-size:13px;line-height:1.7;resize:vertical">${esc(text)}</textarea>
|
||||
<div style="margin-top:12px;text-align:right"><button class="btn" onclick="copyShare()">📋 复制全文</button></div>
|
||||
`);
|
||||
}
|
||||
function copyShare() {
|
||||
const ta = document.querySelector(".share-box");
|
||||
if (ta) copyText(ta.value);
|
||||
}
|
||||
|
||||
/* 清空对话从头开始 */
|
||||
function clearChat() {
|
||||
if (!chatHistory.length) { toast("对话已经是空的"); return; }
|
||||
if (!confirm("确定清空当前对话吗?将从头开始。")) return;
|
||||
chatHistory.length = 0;
|
||||
const list = $("#chat-list");
|
||||
const welcome = document.getElementById("welcome-msg");
|
||||
const w = welcome ? welcome.outerHTML : "";
|
||||
list.innerHTML = w;
|
||||
loadBoot();
|
||||
toast("🗑️ 对话已清空");
|
||||
}
|
||||
$("#share-btn").addEventListener("click", shareChat);
|
||||
$("#clear-btn").addEventListener("click", clearChat);
|
||||
|
||||
/* 快捷问题:点击 → 自动填入输入框并自动提交(需求2) */
|
||||
function askQuick(q) {
|
||||
$("#chat-input").value = q;
|
||||
autoResizeInput();
|
||||
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) => {
|
||||
const act = e.target.closest(".act-btn");
|
||||
if (act) {
|
||||
if (act.title.includes("复制")) copyMsg(act);
|
||||
else if (act.title.includes("重新生成")) regenerate(act);
|
||||
return;
|
||||
}
|
||||
const q = e.target.closest(".quick-q");
|
||||
if (q) { e.preventDefault(); askQuick(q.textContent); return; }
|
||||
const ent = e.target.closest(".entity, .ecard");
|
||||
|
||||
+8
-2
@@ -25,13 +25,19 @@
|
||||
<button class="tab" data-view="persons">👥 人物</button>
|
||||
<button class="tab" data-view="standings">🏆 排名</button>
|
||||
</nav>
|
||||
<a class="admin-link" href="/admin" title="管理后台">⚙️</a>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<!-- ================= 对话 ================= -->
|
||||
<section id="view-chat" class="view active">
|
||||
<div class="chat-wrap">
|
||||
<div class="chat-toolbar">
|
||||
<span class="ct-title">💬 对话</span>
|
||||
<div>
|
||||
<button class="tool-btn" id="share-btn" title="分享对话">🔗 分享</button>
|
||||
<button class="tool-btn" id="clear-btn" title="清空对话从头开始">🗑️ 清空</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="chat-list" class="chat-list">
|
||||
<div class="msg bot" id="welcome-msg">
|
||||
<div class="avatar">🤖</div>
|
||||
@@ -43,7 +49,7 @@
|
||||
</div>
|
||||
<div class="chips" id="chips"></div>
|
||||
<div class="input-bar">
|
||||
<input id="chat-input" type="text" placeholder="输入问题,如:湖人最近比赛怎么样?" autocomplete="off">
|
||||
<textarea id="chat-input" rows="1" placeholder="输入问题,如:湖人最近比赛怎么样?(Enter 发送,Shift+Enter 换行)" autocomplete="off"></textarea>
|
||||
<button id="send-btn">发送</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+30
-16
@@ -25,37 +25,49 @@ main { flex: 1; width: 100%; max-width: 1200px; margin: 0 auto; padding: 20px 16
|
||||
|
||||
/* ---------- 对话 ---------- */
|
||||
.chat-wrap { display: flex; flex-direction: column; height: calc(100vh - 190px); min-height: 480px; }
|
||||
.chat-toolbar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; padding: 0 4px; }
|
||||
.ct-title { color: var(--sub); font-size: 13px; font-weight: 600; letter-spacing: 1px; }
|
||||
.tool-btn { background: var(--bg2); border: 1px solid var(--line); color: var(--sub); border-radius: 999px; padding: 5px 12px; font-size: 12.5px; cursor: pointer; margin-left: 6px; transition: .15s; }
|
||||
.tool-btn:hover { color: var(--orange2); border-color: var(--orange2); }
|
||||
.msg-body { flex: 1; min-width: 0; }
|
||||
.msg-actions { display: flex; align-items: center; gap: 2px; margin-top: 5px; padding-left: 4px; opacity: .8; }
|
||||
.msg.user .msg-actions { justify-content: flex-end; padding-left: 0; padding-right: 4px; }
|
||||
.act-btn { background: transparent; border: none; color: var(--sub); font-size: 13px; cursor: pointer; padding: 3px 6px; border-radius: 6px; line-height: 1; transition: .15s; }
|
||||
.act-btn:hover { color: var(--orange2); background: rgba(249,115,22,.12); }
|
||||
.msg-time { font-size: 11px; color: var(--sub); margin-left: 6px; }
|
||||
#toast { position: fixed; left: 50%; bottom: 100px; transform: translateX(-50%) translateY(12px); background: var(--bg2); border: 1px solid var(--line); color: var(--txt); padding: 9px 20px; border-radius: 999px; font-size: 13px; opacity: 0; pointer-events: none; transition: .25s; z-index: 300; box-shadow: 0 6px 24px rgba(0,0,0,.5); }
|
||||
#toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||||
.chat-list { flex: 1; overflow-y: auto; padding: 8px 4px 16px; display: flex; flex-direction: column; gap: 14px; scroll-behavior: smooth; }
|
||||
.msg { display: flex; gap: 10px; max-width: 88%; }
|
||||
.msg.user { align-self: flex-end; flex-direction: row-reverse; }
|
||||
.avatar { width: 38px; height: 38px; border-radius: 50%; background: var(--card); border: 1px solid var(--line); display: flex; align-items: center; justify-content: center; font-size: 19px; flex-shrink: 0; }
|
||||
.msg.user .avatar { background: linear-gradient(135deg, #f97316, #ea580c); border: none; }
|
||||
.bubble { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 12px 16px; font-size: 14.5px; line-height: 1.75; white-space: pre-wrap; word-break: break-word; }
|
||||
.msg.user .bubble { background: #2a1c10; border-color: #7c3a1e; }
|
||||
.bubble { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 12px 16px; font-size: 14.5px; line-height: 1.55; white-space: normal; word-break: break-word; }
|
||||
.msg.user .bubble { background: #2a1c10; border-color: #7c3a1e; white-space: pre-wrap; }
|
||||
.bubble b { color: var(--orange2); }
|
||||
.bubble em { color: var(--blue); font-style: normal; }
|
||||
.bubble .hint { color: var(--sub); font-size: 13px; margin-top: 6px; }
|
||||
.bubble .quick-q { color: var(--blue); cursor: pointer; text-decoration: none; border-bottom: 1px dashed var(--blue); }
|
||||
.bubble .quick-q:hover { color: var(--orange2); border-bottom-color: var(--orange2); }
|
||||
.bubble ul { margin: 6px 0 6px 18px; }
|
||||
.bubble li { margin: 3px 0; }
|
||||
.bubble ul { margin: 4px 0 4px 18px; }
|
||||
.bubble li { margin: 2px 0; }
|
||||
|
||||
/* ---------- Markdown 渲染(需求3) ---------- */
|
||||
.md { line-height: 1.8; }
|
||||
.md h1, .md h2, .md h3, .md h4 { margin: 12px 0 6px; line-height: 1.4; }
|
||||
.md h1 { font-size: 17px; } .md h2 { font-size: 16px; } .md h3, .md h4 { font-size: 15px; }
|
||||
.md { line-height: 1.6; }
|
||||
.md h1, .md h2, .md h3, .md h4 { margin: 10px 0 4px; line-height: 1.35; }
|
||||
.md h1 { font-size: 16.5px; } .md h2 { font-size: 15.5px; } .md h3, .md h4 { font-size: 14.5px; }
|
||||
.md h1::before, .md h2::before { content: ""; }
|
||||
.md p { margin: 6px 0; }
|
||||
.md ul, .md ol { margin: 6px 0 6px 20px; }
|
||||
.md li { margin: 3px 0; }
|
||||
.md p { margin: 4px 0; }
|
||||
.md ul, .md ol { margin: 4px 0 4px 20px; }
|
||||
.md li { margin: 2px 0; }
|
||||
.md code { background: #0d1117; border: 1px solid var(--line); border-radius: 5px; padding: 1px 6px; font-size: 12.5px; font-family: Consolas, monospace; color: var(--green); }
|
||||
.md pre { background: #0d1117; border: 1px solid var(--line); border-radius: 10px; padding: 12px; overflow-x: auto; margin: 8px 0; }
|
||||
.md pre { background: #0d1117; border: 1px solid var(--line); border-radius: 10px; padding: 10px; overflow-x: auto; margin: 6px 0; }
|
||||
.md pre code { background: transparent; border: none; padding: 0; color: var(--txt); }
|
||||
.md blockquote { border-left: 3px solid var(--orange2); padding: 2px 12px; margin: 8px 0; color: var(--sub); background: rgba(249,115,22,.06); border-radius: 0 8px 8px 0; }
|
||||
.md table { display: block; width: 100%; overflow-x: auto; margin: 10px 0; }
|
||||
.md table th, .md table td { padding: 7px 10px; font-size: 12.5px; }
|
||||
.md blockquote { border-left: 3px solid var(--orange2); padding: 2px 12px; margin: 6px 0; color: var(--sub); background: rgba(249,115,22,.06); border-radius: 0 8px 8px 0; }
|
||||
.md table { display: block; width: 100%; overflow-x: auto; margin: 8px 0; }
|
||||
.md table th, .md table td { padding: 6px 9px; font-size: 12.5px; }
|
||||
.md table th { background: var(--bg2); color: var(--orange2); }
|
||||
.md hr { border: none; border-top: 1px solid var(--line); margin: 10px 0; }
|
||||
.md hr { border: none; border-top: 1px solid var(--line); margin: 8px 0; }
|
||||
.md a { color: var(--blue); text-decoration: none; }
|
||||
.md a:hover { text-decoration: underline; }
|
||||
|
||||
@@ -97,7 +109,9 @@ main { flex: 1; width: 100%; max-width: 1200px; margin: 0 auto; padding: 20px 16
|
||||
.chips button:hover { border-color: var(--orange2); color: var(--orange2); }
|
||||
|
||||
.input-bar { display: flex; gap: 10px; background: var(--bg2); border: 1px solid var(--line); border-radius: 999px; padding: 8px 10px 8px 18px; }
|
||||
#chat-input { flex: 1; background: transparent; border: none; outline: none; color: var(--txt); font-size: 15px; }
|
||||
#chat-input { flex: 1; background: transparent; border: none; outline: none; color: var(--txt); font-size: 15px; line-height: 1.5; resize: none; overflow-y: auto; max-height: 90px; padding: 5px 0; font-family: inherit; }
|
||||
#chat-input::-webkit-scrollbar { width: 5px; }
|
||||
#chat-input::-webkit-scrollbar-thumb { background: var(--line); border-radius: 3px; }
|
||||
#send-btn { background: linear-gradient(135deg, #f97316, #ea580c); border: none; color: #fff; padding: 10px 24px; border-radius: 999px; cursor: pointer; font-size: 14px; font-weight: 600; }
|
||||
#send-btn:disabled { opacity: .5; cursor: wait; }
|
||||
|
||||
|
||||
Reference in New Issue
Block a user