From 2d4f964191a56a7a84f10cc99fe30684611eaa79 Mon Sep 17 00:00:00 2001 From: anor Date: Mon, 8 Jun 2026 15:39:18 +1000 Subject: [PATCH] =?UTF-8?q?fix:=20=D0=B2=D0=B5=D0=B1=20=D0=BD=D0=B5=20?= =?UTF-8?q?=D0=BF=D0=B0=D0=B4=D0=B0=D0=B5=D1=82=20500=20=D0=BF=D1=80=D0=B8?= =?UTF-8?q?=20=D0=BD=D0=B5=D0=B4=D0=BE=D1=81=D1=82=D1=83=D0=BF=D0=BD=D0=BE?= =?UTF-8?q?=D0=BC=20LLM-=D0=B1=D1=8D=D0=BA=D0=B5=D0=BD=D0=B4=D0=B5=20(clau?= =?UTF-8?q?de=20=D0=B2=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5=D0=B9=D0=BD=D0=B5?= =?UTF-8?q?=D1=80=D0=B5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit В контейнере нет CLI claude → ClaudeCliLLM кидал FileNotFoundError → голый HTTP 500. Теперь: ClaudeCliLLM при отсутствии бинаря даёт понятную ошибку; /api/ask и /api/review ловят сбой LLM → HTTP 503 с detail; фронт показывает текст причины вместо «HTTP 500». Тесты +2. Co-Authored-By: Claude Opus 4.8 (1M context) --- frontend/src/api.js | 6 +++++- rag/agent/llm.py | 9 +++++++-- tests/test_agent.py | 8 ++++++++ tests/test_web.py | 11 +++++++++++ web/app.py | 14 ++++++++++---- 5 files changed, 41 insertions(+), 7 deletions(-) diff --git a/frontend/src/api.js b/frontend/src/api.js index ccacf52..c9762a7 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -6,7 +6,11 @@ async function post(path, body) { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }) - if (!r.ok) throw new Error(`${path}: HTTP ${r.status}`) + if (!r.ok) { + let detail = `HTTP ${r.status}` + try { const j = await r.json(); if (j && j.detail) detail = j.detail } catch {} + throw new Error(detail) // показываем причину с сервера, не голый код + } return r.json() } diff --git a/rag/agent/llm.py b/rag/agent/llm.py index d98c95a..02fb4f8 100644 --- a/rag/agent/llm.py +++ b/rag/agent/llm.py @@ -80,8 +80,13 @@ class ClaudeCliLLM: return cmd def __call__(self, system: str, user: str) -> str: - proc = self._runner(self._cmd(system, user), capture_output=True, - text=True, timeout=self.timeout) + try: + proc = self._runner(self._cmd(system, user), capture_output=True, + text=True, timeout=self.timeout) + except FileNotFoundError: + raise RuntimeError("Claude CLI недоступен в этом окружении (нет бинаря " + "`claude`) — используй бэкенд zai или установи claude " + "и задай CLAUDE_CODE_OAUTH_TOKEN") out = (proc.stdout or "").strip() if any(m in out for m in self.NOT_LOGGED) or \ any(m in (proc.stderr or "") for m in self.NOT_LOGGED): diff --git a/tests/test_agent.py b/tests/test_agent.py index fe5aa46..8f43039 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -147,6 +147,14 @@ def test_claude_cli_raises_on_empty_output(): ClaudeCliLLM(runner=runner)("s", "u") +def test_claude_cli_missing_binary_clear_error(): + # нет бинаря claude (как в Docker-контейнере) → понятная ошибка, не FileNotFoundError + def runner(cmd, **kw): + raise FileNotFoundError(2, "No such file or directory", "claude") + with pytest.raises(RuntimeError, match="недоступен"): + ClaudeCliLLM(runner=runner)("s", "u") + + def test_make_llm_selects_backend(): assert isinstance(make_llm("claude"), ClaudeCliLLM) assert isinstance(make_llm("zai"), ZaiLLM) diff --git a/tests/test_web.py b/tests/test_web.py index 6e52b7f..c72e264 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -149,3 +149,14 @@ def test_media_unknown_token_404(tmp_path): assert c.get("/api/media/video/deadbeefdeadbeef").status_code == 404 # путь-traversal не пройдёт: наружу только токены из реестра assert c.get("/api/media/doc/000000000000").status_code == 404 + + +def test_ask_llm_failure_returns_503_not_500(tmp_path): + # недоступный бэкенд (как claude в контейнере) → 503 с понятным detail, не голый 500 + class FailingLLM: + def __call__(self, system, user): + raise RuntimeError("Claude CLI недоступен в этом окружении") + c = TestClient(_app(tmp_path, FailingLLM()), raise_server_exceptions=False) + r = c.post("/api/ask", json={"query": "тест"}) + assert r.status_code == 503 + assert "недоступен" in r.json()["detail"] diff --git a/web/app.py b/web/app.py index 4352bf7..28b999c 100644 --- a/web/app.py +++ b/web/app.py @@ -85,16 +85,22 @@ def create_app(index=None, llm=None, resolver=None, @app.post("/api/ask") def ask(req: AskReq): from rag.agent import answer - res = answer(req.query, _lazy_index(app), _lazy_llm(app, req.backend), - k=req.k, layer=req.layer) + try: + res = answer(req.query, _lazy_index(app), _lazy_llm(app, req.backend), + k=req.k, layer=req.layer) + except Exception as e: # LLM/сервис недоступен → 503 с текстом, + raise HTTPException(503, detail=str(e)) # а не голый 500 (UI покажет причину) return {"answer": res.text, "sources": _enrich(res.sources, _lazy_resolver(app))} @app.post("/api/review") def review_ep(req: ReviewReq): from rag.agent import review - res = review(req.design, _lazy_index(app), _lazy_llm(app, req.backend), - k=req.k) + try: + res = review(req.design, _lazy_index(app), _lazy_llm(app, req.backend), + k=req.k) + except Exception as e: + raise HTTPException(503, detail=str(e)) return {"parsed": res.parsed, "raw": res.raw, "violations": res.violations, "safety_warnings": res.safety_warnings, "sources": _enrich(res.sources, _lazy_resolver(app))}