fix: 会话落库/加载缺 app context——后台线程 db 操作必须包 _flask_app.app_context()(历史加载与完成写回两处),否则静默失败(消息不落库、标题不生成)
This commit is contained in:
+14
-10
@@ -847,7 +847,9 @@ def _agent_thread(run_id, prompt, serial, cfg):
|
|||||||
# 历史来源:绑定了会话 → 从会话读(多轮上下文延续,DeepSeek 式);
|
# 历史来源:绑定了会话 → 从会话读(多轮上下文延续,DeepSeek 式);
|
||||||
# 无会话(CLI/兼容)→ 用运行态 history
|
# 无会话(CLI/兼容)→ 用运行态 history
|
||||||
if conv_id:
|
if conv_id:
|
||||||
msgs = _conv_msgs(conv_id)
|
# 后台线程需自行推 app context(与 _find_experiences 同思路)
|
||||||
|
with _flask_app.app_context():
|
||||||
|
msgs = _conv_msgs(conv_id)
|
||||||
history = [{"role": m.get("role"), "content": m.get("content", "")[:4000]}
|
history = [{"role": m.get("role"), "content": m.get("content", "")[:4000]}
|
||||||
for m in (msgs or []) if m.get("role") in ("user", "assistant")]
|
for m in (msgs or []) if m.get("role") in ("user", "assistant")]
|
||||||
history = history[-24:]
|
history = history[-24:]
|
||||||
@@ -886,16 +888,18 @@ def _agent_thread(run_id, prompt, serial, cfg):
|
|||||||
hist.append({"role": "user", "content": prompt[:2000]})
|
hist.append({"role": "user", "content": prompt[:2000]})
|
||||||
hist.append({"role": "assistant", "content": (answer or "")[:4000]})
|
hist.append({"role": "assistant", "content": (answer or "")[:4000]})
|
||||||
_run["history"] = hist[-24:]
|
_run["history"] = hist[-24:]
|
||||||
# 会话落库:本轮追加写回(新会话自动用首条消息作标题)
|
# 会话落库:本轮追加写回(新会话自动用首条消息作标题)。
|
||||||
if conv_id:
|
# 后台线程 db 访问需 app context。
|
||||||
|
if conv_id and _flask_app is not None:
|
||||||
try:
|
try:
|
||||||
saved = list(_run["history"])
|
with _flask_app.app_context():
|
||||||
title = None
|
saved = list(_run["history"])
|
||||||
if not db.session.execute(db.text(
|
title = None
|
||||||
"SELECT title FROM agent_conversation WHERE id=:i"),
|
if not db.session.execute(db.text(
|
||||||
{"i": conv_id}).scalar():
|
"SELECT title FROM agent_conversation WHERE id=:i"),
|
||||||
title = "".join(prompt.split())[:30] or "新会话"
|
{"i": conv_id}).scalar():
|
||||||
_conv_save_messages(conv_id, saved, title=title)
|
title = "".join(prompt.split())[:30] or "新会话"
|
||||||
|
_conv_save_messages(conv_id, saved, title=title)
|
||||||
_log.info(f"会话已保存: {conv_id}({len(saved)} 条消息)")
|
_log.info(f"会话已保存: {conv_id}({len(saved)} 条消息)")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
_log.warning(f"会话落库失败: {e}")
|
_log.warning(f"会话落库失败: {e}")
|
||||||
|
|||||||
Reference in New Issue
Block a user