样式修改
This commit is contained in:
1 parent
114ee8f6ac
commit
e3d8e534f6
6 files changed
+739
-48
No files matched your search
@@ -66,6 +66,7 @@ from fastapi.responses import StreamingResponse
|
||||
from app.gateway.routers.multi_agent import (
|
||||
_auth_headers,
|
||||
_create_thread,
|
||||
_diagnose_exception,
|
||||
_find_dispatch_message,
|
||||
_find_trailing_ai_text,
|
||||
_flatten_content,
|
||||
@@ -112,8 +113,20 @@ async def init_intent(request: Request, payload: dict = Body(...)) -> dict[str,
|
||||
# on the dev machine) makes httpx route loopback calls through an upstream
|
||||
# proxy that can't reach 127.0.0.1, costing 40+ seconds of timeout per
|
||||
# request before falling back. Symptom in logs: `headers_in=42.160s`.
|
||||
async with httpx.AsyncClient(timeout=None, trust_env=False) as client:
|
||||
thread_id = await _create_thread(client, base, headers)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=None, trust_env=False) as client:
|
||||
thread_id = await _create_thread(client, base, headers)
|
||||
except HTTPException:
|
||||
# 上游已用结构化方式失败,原样传给前端不需要二次包装。
|
||||
raise
|
||||
except Exception as exc:
|
||||
# 把根因暴露给前端而不是吞成裸 500——内网部署常见的「config.yaml 模型外网不通」
|
||||
# / 「内置 agent 目录缺失」/ 「loopback 走代理」都能在前端面板直接看到。
|
||||
# FastAPI 把 detail=dict 序列化为 {"detail": {...}};前端 initIntent
|
||||
# 在 !res.ok 分支里读 detail.hint / trace_tail 渲染诊断面板。
|
||||
diagnostic = _diagnose_exception(exc, context="intent_init")
|
||||
logger.error("intent init failed: %s", diagnostic, exc_info=exc)
|
||||
raise HTTPException(status_code=500, detail=diagnostic) from exc
|
||||
return {
|
||||
"status": "success",
|
||||
"agent_id": INTENT_AGENT_ID,
|
||||
@@ -270,11 +283,40 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
|
||||
except HTTPException as exc:
|
||||
logger.warning("intent stream HTTPException: %s %s", exc.status_code, exc.detail)
|
||||
err = {"status": "error", "content": f"[{exc.status_code}] {exc.detail}", "summary": None}
|
||||
# HTTPException 的 detail 可能本身就是 dict(上游已结构化),也可能是 str。
|
||||
# 统一包装成与 _diagnose_exception 同构的字段,便于前端按一种模型渲染。
|
||||
detail_payload: Any = exc.detail
|
||||
error_detail: dict[str, Any]
|
||||
if isinstance(detail_payload, dict) and "code" in detail_payload:
|
||||
error_detail = detail_payload
|
||||
else:
|
||||
error_detail = {
|
||||
"code": "http_exception",
|
||||
"message": f"[{exc.status_code}] {detail_payload}",
|
||||
"exception_type": "HTTPException",
|
||||
"exception_repr": repr(exc),
|
||||
"root_type": None,
|
||||
"root_repr": None,
|
||||
"hint": None,
|
||||
"trace_tail": [],
|
||||
"context": "intent_stream",
|
||||
}
|
||||
err = {
|
||||
"status": "error",
|
||||
"content": error_detail["message"],
|
||||
"summary": None,
|
||||
"error_detail": error_detail,
|
||||
}
|
||||
yield f"data: {json.dumps(err, ensure_ascii=False)}\n\n"
|
||||
except Exception as exc:
|
||||
logger.exception("intent stream unexpected failure")
|
||||
err = {"status": "error", "content": f"unexpected: {exc!r}", "summary": None}
|
||||
diagnostic = _diagnose_exception(exc, context="intent_stream")
|
||||
logger.error("intent stream failed: %s", diagnostic, exc_info=exc)
|
||||
err = {
|
||||
"status": "error",
|
||||
"content": diagnostic["message"],
|
||||
"summary": None,
|
||||
"error_detail": diagnostic,
|
||||
}
|
||||
yield f"data: {json.dumps(err, ensure_ascii=False)}\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
|
||||
@@ -51,6 +51,7 @@ import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
import traceback
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
import httpx
|
||||
@@ -62,6 +63,101 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/api/multi-agent", tags=["multi-agent"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 共享:异常诊断器(intent/recommend/multi-agent 共用)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _diagnose_exception(exc: BaseException, *, context: str = "") -> dict[str, Any]:
|
||||
"""把后端异常转成结构化诊断 dict,直接给前端展示用。
|
||||
|
||||
设计目标:让运维 / 前端开发不用翻 backend 日志就能看到根因和处置建议。
|
||||
返回字段:
|
||||
- code: 短稳定分类(loopback_connect_failed / upstream_connect_failed / ...)
|
||||
- message: 一行人类可读
|
||||
- exception_type: 表层异常类名
|
||||
- exception_repr: repr(exc)
|
||||
- root_type / root_repr: 沿 __cause__ 链找到的最深异常(若与表层不同)
|
||||
- hint: 针对常见失败模式的可执行建议(中文)
|
||||
- trace_tail: traceback 最后 ~12 行(避免响应体过大)
|
||||
- context: 调用方标签(如 "intent_init")
|
||||
"""
|
||||
exc_type = type(exc).__name__
|
||||
exc_repr = repr(exc)
|
||||
|
||||
# 沿 __cause__ 链找最深异常:httpx 经常把 ConnectError 包成 RemoteProtocolError 等。
|
||||
root: BaseException = exc
|
||||
seen: set[int] = {id(root)}
|
||||
while getattr(root, "__cause__", None) is not None and id(root.__cause__) not in seen:
|
||||
root = root.__cause__ # type: ignore[assignment]
|
||||
seen.add(id(root))
|
||||
|
||||
code = "unexpected"
|
||||
hint = "查看 trace_tail 最后一帧定位代码位置;若信息不足请到 backend 日志找完整 traceback。"
|
||||
|
||||
if isinstance(root, httpx.ConnectError):
|
||||
target = str(root).strip().lower()
|
||||
# loopback 失败 = Gateway 自己没起 / 代理拦回环;outbound 失败 = LLM 提供商不可达。
|
||||
if "127.0.0.1" in target or "localhost" in target or "loopback" in target:
|
||||
code = "loopback_connect_failed"
|
||||
hint = (
|
||||
"本地 Gateway loopback 连接失败:确认后端进程在 8001 端口监听;"
|
||||
"另检查 HTTP_PROXY / HTTPS_PROXY 是否把 127.0.0.1 也走了代理"
|
||||
"(代码已显式 trust_env=False,理论上不该走代理)。"
|
||||
)
|
||||
else:
|
||||
code = "upstream_connect_failed"
|
||||
hint = (
|
||||
"外网/上游服务连接失败:大概率是 LLM 提供商不可达"
|
||||
"(如 api.deepseek.com 在内网被防火墙拦截)。"
|
||||
"把 config.yaml 里所有 base_url 改成内网可达的 LLM endpoint,"
|
||||
"或加白名单/正向代理(HTTPS_PROXY)。"
|
||||
)
|
||||
elif isinstance(root, httpx.TimeoutException):
|
||||
code = "upstream_timeout"
|
||||
hint = (
|
||||
"上游请求超时:网络抖动 / 模型推理过慢。"
|
||||
"先 curl <base_url>/v1/models 确认可达,再看模型是否过载或 max_tokens 过大。"
|
||||
)
|
||||
elif isinstance(root, httpx.HTTPStatusError):
|
||||
code = "upstream_http_error"
|
||||
status = getattr(getattr(root, "response", None), "status_code", "?")
|
||||
hint = (
|
||||
f"上游接口返回 HTTP {status}:可能是 API key 失效、模型名不对、"
|
||||
"或目标服务自身报错。查看 backend 日志里 response.text 拿详细错误体。"
|
||||
)
|
||||
elif isinstance(root, FileNotFoundError):
|
||||
code = "file_not_found"
|
||||
hint = (
|
||||
f"找不到路径:{root}。常见原因:内置 agent 目录(.deer-flow/agents/<id>/)缺失,"
|
||||
"或 SOUL.md 没拷过来;详见后端开发文档 §11.7。"
|
||||
)
|
||||
elif isinstance(root, KeyError):
|
||||
code = "key_error"
|
||||
hint = (
|
||||
f"缺少 key:{root}。若 key 是 agent_name/agent_id 类:大概率内置 agent 目录缺失;"
|
||||
"若是配置 key:检查 config.yaml schema。"
|
||||
)
|
||||
elif isinstance(root, ValueError) and "model" in str(root).lower():
|
||||
code = "no_models_configured"
|
||||
hint = "config.yaml 没有任何 models[],或所有条目都解析失败。检查 yaml 语法与 $ENV 引用。"
|
||||
|
||||
trace_lines = traceback.format_exception(type(exc), exc, exc.__traceback__)
|
||||
trace_tail = "".join(trace_lines).splitlines()[-12:]
|
||||
|
||||
return {
|
||||
"code": code,
|
||||
"message": f"{exc_type}: {exc}" if str(exc) else exc_type,
|
||||
"exception_type": exc_type,
|
||||
"exception_repr": exc_repr,
|
||||
"root_type": type(root).__name__ if root is not exc else None,
|
||||
"root_repr": repr(root) if root is not exc else None,
|
||||
"hint": hint,
|
||||
"trace_tail": trace_tail,
|
||||
"context": context or None,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Loopback 辅助函数(Gateway → Gateway,同进程)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in new issue
Block a user