diff --git a/Dockerfile b/Dockerfile index 0d07f9e..0484fbf 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,17 +15,15 @@ RUN npm run build FROM python:3.11-slim WORKDIR /app -# ngspice — Фаза 4 (симуляция); curl — для установщика Claude CLI +# ngspice — системный, нужен Фазе 4 (симуляция схем) RUN apt-get update \ - && apt-get install -y --no-install-recommends ngspice curl \ + && apt-get install -y --no-install-recommends ngspice \ && rm -rf /var/lib/apt/lists/* -# Claude Code (нативный бинарь, без node) — для LLM-бэкенда `claude` в вебе. -# Работает headless по CLAUDE_CODE_OAUTH_TOKEN (берётся из .env через rag.config). -RUN curl -fsSL https://claude.ai/install.sh | bash -ENV PATH="/root/.local/bin:${PATH}" \ - HOME=/root \ - DISABLE_ANALYTICS=1 +# Claude CLI в образ НЕ ставится: с сервера Anthropic геоблокирован (api.anthropic.com +# → 403, claude.ai → «unavailable in region»). Бэкенд `claude` работает только там, +# где есть маршрут до Anthropic (мак через прокси). Чтобы включить на сервере — нужен +# HTTPS_PROXY/VPN до Anthropic + установка claude + CLAUDE_CODE_OAUTH_TOKEN (см. DEPLOY). # torch CPU-сборкой (без CUDA) ДО requirements RUN pip install --no-cache-dir torch==2.7.1 \ diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 64b44b4..3d7e260 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1,16 +1,25 @@ -import React, { useState } from 'react' -import { ask, review } from './api.js' +import React, { useEffect, useState } from 'react' +import { ask, review, getBackends } from './api.js' import { AnswerText, SourceList } from './Sources.jsx' import MediaModal from './MediaModal.jsx' +const BACKEND_LABEL = { zai: 'Z.AI (быстро)', claude: 'Claude (точнее)' } + export default function App() { const [mode, setMode] = useState('ask') // 'ask' | 'review' - const [backend, setBackend] = useState('zai') // 'zai' | 'claude' + const [backends, setBackends] = useState(['zai']) // доступные (сервер решает) + const [backend, setBackend] = useState('zai') const [input, setInput] = useState('') const [items, setItems] = useState([]) // история {q, kind, ...result} const [busy, setBusy] = useState(false) const [media, setMedia] = useState(null) // открытый медиа в модалке + useEffect(() => { + getBackends().then((b) => { + if (b.backends?.length) { setBackends(b.backends); setBackend(b.default || b.backends[0]) } + }) + }, []) + async function submit(e) { e?.preventDefault() const text = input.trim() @@ -44,8 +53,9 @@ export default function App() { diff --git a/frontend/src/api.js b/frontend/src/api.js index c9762a7..86393f8 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -20,6 +20,15 @@ export const ask = (query, opts = {}) => export const review = (design, opts = {}) => post('/api/review', { design, backend: opts.backend ?? null }) +// какие LLM-бэкенды реально доступны в этом окружении (сервер решает) +export async function getBackends() { + try { + const r = await fetch('/api/backends') + if (r.ok) return r.json() + } catch {} + return { backends: ['zai'], default: 'zai' } +} + export const mediaUrl = (m) => m.kind === 'video' ? `/api/media/video/${m.token}${m.seconds != null ? `#t=${m.seconds}` : ''}` diff --git a/rag/config.py b/rag/config.py index c6130bf..6508b3e 100644 --- a/rag/config.py +++ b/rag/config.py @@ -73,6 +73,12 @@ ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-4.6") LLM_BACKEND = os.environ.get("LLM_BACKEND", "zai") CLAUDE_CLI_MODEL = os.environ.get("CLAUDE_CLI_MODEL", "") # пусто = модель по умолч. +# Какие LLM-бэкенды показывать/разрешать в вебе. По умолчанию только "zai": +# claude доступен лишь там, где есть маршрут до Anthropic (на сервере геоблок 403). +# Включить claude в вебе: WEB_BACKENDS="zai,claude" (+ прокси до Anthropic + токен). +WEB_BACKENDS = [b.strip() for b in os.environ.get("WEB_BACKENDS", "zai").split(",") + if b.strip()] + # Веб-слой: корень медиа (видео-дерево + документы) для просмотра оригиналов. # На сервере монтируется томом; локально по умолчанию data/media. MEDIA_ROOT = _resolve(os.environ.get("MEDIA_ROOT"), DATA / "media") diff --git a/tests/test_web.py b/tests/test_web.py index 6805974..a728554 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -161,6 +161,21 @@ def test_media_unknown_token_404(tmp_path): assert c.get("/api/media/doc/000000000000").status_code == 404 +def test_backends_endpoint_lists_available(tmp_path): + c = TestClient(_app(tmp_path, FakeLLM("x"))) + data = c.get("/api/backends").json() + assert "zai" in data["backends"] # по умолчанию только zai + assert data["default"] in data["backends"] + + +def test_ask_rejects_unavailable_backend(tmp_path): + # claude недоступен в этом окружении (WEB_BACKENDS=zai) → 400, не запуск + c = TestClient(_app(tmp_path, FakeLLM("x")), raise_server_exceptions=False) + r = c.post("/api/ask", json={"query": "тест", "backend": "claude"}) + assert r.status_code == 400 + assert "недоступен" in r.json()["detail"] + + def test_ask_llm_failure_returns_503_not_500(tmp_path): # недоступный бэкенд (как claude в контейнере) → 503 с понятным detail, не голый 500 class FailingLLM: diff --git a/web/app.py b/web/app.py index 4ce2513..7086cf8 100644 --- a/web/app.py +++ b/web/app.py @@ -101,9 +101,23 @@ def create_app(index=None, llm=None, resolver=None, else None), "media": len(_lazy_resolver(app).registry)} + @app.get("/api/backends") + def backends(): + from rag import config + return {"backends": config.WEB_BACKENDS, + "default": (config.LLM_BACKEND if config.LLM_BACKEND in config.WEB_BACKENDS + else (config.WEB_BACKENDS[0] if config.WEB_BACKENDS else "zai"))} + + def _check_backend(backend: str | None): + from rag import config + if backend and backend not in config.WEB_BACKENDS: + raise HTTPException(400, f"бэкенд '{backend}' недоступен в этом окружении " + f"(доступны: {', '.join(config.WEB_BACKENDS)})") + @app.post("/api/ask") def ask(req: AskReq): from rag.agent import answer + _check_backend(req.backend) try: res = answer(req.query, _lazy_index(app), _lazy_llm(app, req.backend), k=req.k, layer=req.layer) @@ -115,6 +129,7 @@ def create_app(index=None, llm=None, resolver=None, @app.post("/api/review") def review_ep(req: ReviewReq): from rag.agent import review + _check_backend(req.backend) try: res = review(req.design, _lazy_index(app), _lazy_llm(app, req.backend), k=req.k)