fix: stabilize AI coach chat against truncation and empty replies

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-06-11 06:27:06 +08:00
parent 7f1015f852
commit 401ee2f130
7 changed files with 111 additions and 32 deletions
+22 -4
View File
@@ -7,6 +7,7 @@ from hub_ai.attachments import parse_chat_attachments
from hub_ai.client import generate_text, model_label
from hub_ai.config import (
CHAT_CONTEXT_MAX_CHARS,
CHAT_HISTORY_MAX_CHARS_PER_MSG,
CHAT_MAX_CONTINUATIONS,
CHAT_MAX_HISTORY_TURNS,
CHAT_MAX_OUTPUT_TOKENS,
@@ -25,17 +26,31 @@ from hub_ai.store import (
)
def _history_lines(messages: list[dict], max_turns: int = CHAT_MAX_HISTORY_TURNS) -> str:
def _is_ai_error_reply(text: str) -> bool:
t = (text or "").strip()
return t.startswith("AI 调用失败") or t.startswith("AI 生成失败")
def _history_lines(
messages: list[dict],
max_turns: int = CHAT_MAX_HISTORY_TURNS,
*,
max_chars_per_msg: int = 1500,
) -> str:
rows = [m for m in (messages or []) if m.get("role") in ("user", "assistant")]
rows = rows[-max_turns * 2 :]
lines = []
for m in rows:
role = "用户" if m.get("role") == "user" else "搭档"
content = m.get("content") or ""
content = str(m.get("content") or "").strip()
if m.get("role") == "assistant" and _is_ai_error_reply(content):
continue
att = m.get("attachments") or []
if att:
names = "".join(str(a.get("name") or "附件") for a in att[:3])
content = f"{content} [附件: {names}]".strip()
if len(content) > max_chars_per_msg:
content = content[: max_chars_per_msg - 1].rstrip() + ""
lines.append(f"{role}{content}")
return "\n".join(lines)
@@ -79,7 +94,10 @@ def send_chat_message(
day = ctx["trading_day"]
session = ensure_active_session(trading_day=day)
sid = session["id"]
history = _history_lines(session.get("messages") or [])
history = _history_lines(
session.get("messages") or [],
max_chars_per_msg=CHAT_HISTORY_MAX_CHARS_PER_MSG,
)
append_chat_message(
sid,
@@ -110,7 +128,7 @@ def send_chat_message(
max_tokens=CHAT_MAX_OUTPUT_TOKENS,
max_continuations=CHAT_MAX_CONTINUATIONS,
)
if reply.startswith("AI 调用失败"):
if _is_ai_error_reply(reply):
return {"ok": False, "msg": reply, "session_id": sid}
session = append_chat_message(sid, "assistant", reply)