From caa646e89cbe2a1ae84a88dd12e779f7b34c5399 Mon Sep 17 00:00:00 2001 From: butubb <1422726308@qq.com> Date: Sun, 6 Sep 2026 15:14:30 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BC=9A=E8=AF=9D=E8=90=BD=E5=BA=93/?= =?UTF-8?q?=E5=8A=A0=E8=BD=BD=E7=BC=BA=20app=20context=E2=80=94=E2=80=94?= =?UTF-8?q?=E5=90=8E=E5=8F=B0=E7=BA=BF=E7=A8=8B=20db=20=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E5=BF=85=E9=A1=BB=E5=8C=85=20=5Fflask=5Fapp.app=5Fcontext()?= =?UTF-8?q?=EF=BC=88=E5=8E=86=E5=8F=B2=E5=8A=A0=E8=BD=BD=E4=B8=8E=E5=AE=8C?= =?UTF-8?q?=E6=88=90=E5=86=99=E5=9B=9E=E4=B8=A4=E5=A4=84=EF=BC=89=EF=BC=8C?= =?UTF-8?q?=E5=90=A6=E5=88=99=E9=9D=99=E9=BB=98=E5=A4=B1=E8=B4=A5=EF=BC=88?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E4=B8=8D=E8=90=BD=E5=BA=93=E3=80=81=E6=A0=87?= =?UTF-8?q?=E9=A2=98=E4=B8=8D=E7=94=9F=E6=88=90=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/agent_api.py | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) 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}")