fix(agent): 增强 LLM 流式回复兜底
This commit is contained in:
@@ -219,26 +219,52 @@ def stream_message(conversation: Conversation, content: str):
|
||||
)
|
||||
return
|
||||
|
||||
stream_failed = False
|
||||
stream_error = ""
|
||||
try:
|
||||
for chunk in stream_reply(conversation, content):
|
||||
assistant_parts.append(chunk)
|
||||
yield sse_event("chunk", {"delta": chunk})
|
||||
except (LLMConfigurationError, LLMRequestError) as exc:
|
||||
fallback = f"模型调用失败:{exc}"
|
||||
assistant_parts = [fallback]
|
||||
stream_failed = True
|
||||
stream_error = str(exc)
|
||||
logger.warning(
|
||||
"LLM stream failed",
|
||||
extra={"conversation_id": conversation.pk, "error": str(exc)},
|
||||
)
|
||||
yield sse_event("error", {"message": fallback})
|
||||
except Exception as exc:
|
||||
fallback = f"回复生成中断:{exc}"
|
||||
assistant_parts.append("\n\n" + fallback)
|
||||
stream_failed = True
|
||||
stream_error = str(exc)
|
||||
logger.exception(
|
||||
"Unexpected stream failure",
|
||||
extra={"conversation_id": conversation.pk, "error": str(exc)},
|
||||
)
|
||||
yield sse_event("error", {"message": fallback})
|
||||
|
||||
if stream_failed:
|
||||
try:
|
||||
fallback_reply = generate_reply(conversation, content)
|
||||
assistant_parts = [fallback_reply]
|
||||
logger.info(
|
||||
"Non-stream fallback reply succeeded",
|
||||
extra={"conversation_id": conversation.pk, "content_length": len(fallback_reply)},
|
||||
)
|
||||
yield sse_event("replace", {"content": fallback_reply})
|
||||
except (LLMConfigurationError, LLMRequestError) as exc:
|
||||
fallback = f"模型调用失败:{exc}"
|
||||
assistant_parts = [fallback]
|
||||
logger.warning(
|
||||
"Non-stream fallback reply failed",
|
||||
extra={"conversation_id": conversation.pk, "error": str(exc), "stream_error": stream_error},
|
||||
)
|
||||
yield sse_event("error", {"message": fallback})
|
||||
except Exception as exc:
|
||||
fallback = f"回复生成中断:{stream_error or exc}"
|
||||
assistant_parts.append("\n\n" + fallback)
|
||||
logger.exception(
|
||||
"Non-stream fallback crashed",
|
||||
extra={"conversation_id": conversation.pk, "error": str(exc), "stream_error": stream_error},
|
||||
)
|
||||
yield sse_event("error", {"message": fallback})
|
||||
|
||||
assistant_message = append_assistant_message(conversation, "".join(assistant_parts).strip())
|
||||
|
||||
|
||||
Reference in New Issue
Block a user