fix: веб не падает 500 при недоступном LLM-бэкенде (claude в контейнере)

В контейнере нет 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) <noreply@anthropic.com>
This commit is contained in:
anor
2026-06-08 15:39:18 +10:00
co-authored by Claude Opus 4.8
parent dc9eed721f
commit 2d4f964191
5 changed files with 41 additions and 7 deletions
+5 -1
View File
@@ -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()
}
+7 -2
View File
@@ -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):
+8
View File
@@ -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)
+11
View File
@@ -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"]
+10 -4
View File
@@ -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))}