diff --git a/web/agent_api.py b/web/agent_api.py index be0449c..a82d11e 100644 --- a/web/agent_api.py +++ b/web/agent_api.py @@ -847,7 +847,9 @@ def _agent_thread(run_id, prompt, serial, cfg): # 历史来源:绑定了会话 → 从会话读(多轮上下文延续,DeepSeek 式); # 无会话(CLI/兼容)→ 用运行态 history 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]} for m in (msgs or []) if m.get("role") in ("user", "assistant")] 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": "assistant", "content": (answer or "")[:4000]}) _run["history"] = hist[-24:] - # 会话落库:本轮追加写回(新会话自动用首条消息作标题) - if conv_id: + # 会话落库:本轮追加写回(新会话自动用首条消息作标题)。 + # 后台线程 db 访问需 app context。 + if conv_id and _flask_app is not None: try: - saved = list(_run["history"]) - title = None - if not db.session.execute(db.text( - "SELECT title FROM agent_conversation WHERE id=:i"), - {"i": conv_id}).scalar(): - title = "".join(prompt.split())[:30] or "新会话" - _conv_save_messages(conv_id, saved, title=title) + with _flask_app.app_context(): + saved = list(_run["history"]) + title = None + if not db.session.execute(db.text( + "SELECT title FROM agent_conversation WHERE id=:i"), + {"i": conv_id}).scalar(): + title = "".join(prompt.split())[:30] or "新会话" + _conv_save_messages(conv_id, saved, title=title) _log.info(f"会话已保存: {conv_id}({len(saved)} 条消息)") except Exception as e: _log.warning(f"会话落库失败: {e}")