Commit a1a57512 by 黄南光

修复前端会话缺失以及流式输出问题

1 parent eb45b9c5
...@@ -661,15 +661,30 @@ export default function EnterpriseWiki() { ...@@ -661,15 +661,30 @@ export default function EnterpriseWiki() {
if (!response.body) throw new Error("ReadableStream not supported"); if (!response.body) throw new Error("ReadableStream not supported");
// 检查 HTTP 状态码,若后端返回错误直接提示
if (!response.ok) {
const errData = await response.json().catch(() => ({ detail: `服务器错误 ${response.status}` }));
throw new Error(errData.detail || `服务器错误 ${response.status}`);
}
const reader = response.body.getReader(); const reader = response.body.getReader();
const decoder = new TextDecoder(); const decoder = new TextDecoder();
let aiResponse = ""; let aiResponse = "";
let buffer = ""; let buffer = "";
const messageMap: Record<string, string> = {}; const messageMap: Record<string, string> = {};
// 超时保护:90 秒内没有任何 SSE 数据则自动断开
const TIMEOUT_MS = 90_000;
let lastEventTime = Date.now();
while (true) { while (true) {
// 检查超时
if (Date.now() - lastEventTime > TIMEOUT_MS) {
reader.cancel();
throw new Error("等待响应超时(90秒),请检查后端服务是否正常运行。");
}
const { value, done } = await reader.read(); const { value, done } = await reader.read();
if (done) break; if (done) break;
lastEventTime = Date.now(); // 收到数据,刷新计时
buffer += decoder.decode(value, { stream: true }); buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n"); const lines = buffer.split("\n");
......
...@@ -141,11 +141,15 @@ async def run_wiki_query_stream(user_query: str, history: list): ...@@ -141,11 +141,15 @@ async def run_wiki_query_stream(user_query: str, history: list):
流式执行 Wiki 查询。返回一个异步生成器,产出 Server-Sent Events (SSE) 字符串。 流式执行 Wiki 查询。返回一个异步生成器,产出 Server-Sent Events (SSE) 字符串。
问题9:使用 token_counter_context 追踪 Token 消耗。 问题9:使用 token_counter_context 追踪 Token 消耗。
""" """
# 立即发送 INIT 事件,让前端确认连接已建立,避免因 Agent 初始化慢导致前端看起来无反应
yield "data: [INIT]\n\n"
# 问题9:Token 追踪 # 问题9:Token 追踪
async with token_counter_context() as get_tokens: async with token_counter_context() as get_tokens:
agent = build_query_agent(history) agent = build_query_agent(history)
queue = asyncio.Queue() queue = asyncio.Queue()
pending_thought = None pending_thought = None
final_answer_sent = False # 防止最终答案被重复发送
def flush_pending_thought(): def flush_pending_thought():
nonlocal pending_thought nonlocal pending_thought
...@@ -166,8 +170,22 @@ async def run_wiki_query_stream(user_query: str, history: list): ...@@ -166,8 +170,22 @@ async def run_wiki_query_stream(user_query: str, history: list):
else: else:
queue.put_nowait({"id": item_id, "type": "thought", "content": str(item)}) queue.put_nowait({"id": item_id, "type": "thought", "content": str(item)})
def _extract_text_from_content(content) -> str:
"""从 msg.content 中提取纯文本字符串"""
if isinstance(content, str):
return content
if isinstance(content, list):
parts = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict) and "text" in item:
parts.append(item["text"])
return "".join(parts)
return ""
def message_handler(msg: Msg): def message_handler(msg: Msg):
nonlocal pending_thought nonlocal pending_thought, final_answer_sent
if msg.role == "user": if msg.role == "user":
return return
...@@ -188,6 +206,22 @@ async def run_wiki_query_stream(user_query: str, history: list): ...@@ -188,6 +206,22 @@ async def run_wiki_query_stream(user_query: str, history: list):
is_tool = True is_tool = True
if is_pure_text and not is_tool: if is_pure_text and not is_tool:
# 检测是否是最终答案(以 Final Answer: 开头)
# 如果是,则直接流式发送,不存入 pending_thought(避免先出现在思考折叠框后再重复输出)
raw_text = _extract_text_from_content(content)
cleaned = re.sub(r"^Final Answer:\s*", "", raw_text, flags=re.IGNORECASE).strip()
if cleaned != raw_text.strip(): # 说明确实以 Final Answer: 开头
# 这是最终答案:先 flush 之前暂存的中间思考,再流式发送最终答案
flush_pending_thought()
if cleaned:
final_answer_sent = True
logger.info(f"[Agent WikiAssistant Final Answer via handler] {cleaned[:200]}...")
m_id = f"msg-{datetime.now().timestamp()}"
chunk_size = 4
for i in range(0, len(cleaned), chunk_size):
queue.put_nowait({"id": m_id, "type": "stream", "content": cleaned[i:i+chunk_size]})
return
# 普通中间思考文本:暂存到 pending_thought
pending_thought = msg pending_thought = msg
return return
...@@ -303,6 +337,8 @@ async def run_wiki_query_stream(user_query: str, history: list): ...@@ -303,6 +337,8 @@ async def run_wiki_query_stream(user_query: str, history: list):
await asyncio.sleep(0.01) await asyncio.sleep(0.01)
return return
# 兜底:message_handler 未能拦截到 Final Answer 时,从 final_res 中提取
if not final_answer_sent:
fc = _extract_text(final_res.content if hasattr(final_res, "content") else str(final_res)) fc = _extract_text(final_res.content if hasattr(final_res, "content") else str(final_res))
if fc: if fc:
fc = re.sub(r"^Final Answer:\s*", "", fc, flags=re.IGNORECASE).strip() fc = re.sub(r"^Final Answer:\s*", "", fc, flags=re.IGNORECASE).strip()
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!