4b0d56ff0e
Этап 1 миграции TestingWebApp на целевой стек (Python/Flask/Jinja),
БД остаётся clinic_tests.
E1.0 — База Flask-приложения: SQLAlchemy/psycopg2 пул, Flask sessions,
фабрика create_app, blueprint main с / и /health, base.html в стиле
кабинета HR (Tailwind CDN + Manrope + Material Symbols), 404/500.
E1.1 — Auth + /api/me: Flask sessions (signed cookie) вместо JWT,
bcrypt + Werkzeug, опц. HR_AUTH=1 с UPSERT в clinic_tests.users по
staff_id. UI /login, JSON /api/auth/{login,logout,me}, декораторы
@login_required / @require_role.
E1.2 — Тесты: список + редактор. 10 эндпоинтов, сервисы test_draft,
test_access, test_chain, ai_editor, llm_client, draft_validator,
editor_content. UI /tests (каталог + создание) и /tests/<id>/edit
(редактор с AI). Полный мобильный UX (аккордеоны/drag-n-drop) — в E1.7.
E1.3 — Импорт документов: pypdf + python-docx, эндпоинт
POST /api/tests/import/document, кнопка «Импорт документа» в
AI-панели редактора, лимит 16 МБ.
E1.8 — AI v2: страница /settings (статус ENV-ключа + ping),
ai/generate-by-title (без сетки), ai/check (рецензия), ai/improve
(массовое было→стало с чекбоксами). Унифицированный ответ AI-ошибок:
{ error, code, settingsUrl }.
Docker:
- docker-compose.dev.yml: добавлены DATABASE_URL, HR_AUTH/HR_DATABASE_URL,
DEEPSEEK_API_KEY/OPENAI_API_KEY/LLM_BASE_URL/LLM_MODEL и сеть postgres
для testing-flask.
Документация:
- docs/migration-final.md — двух-этапный план (Этап 1: унификация
стека внутри TestingWebApp; Этап 2: слияние с tgFlaskForm).
- docs/migration-final-inventory.md — карта 22 эндпоинтов Express.
Made-with: Cursor
157 lines
4.8 KiB
Python
157 lines
4.8 KiB
Python
"""OpenAI-совместимый клиент Chat Completions (порт `services/llmClient.js`)."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from dataclasses import dataclass
|
|
from typing import Optional
|
|
|
|
import urllib.request
|
|
import urllib.error
|
|
import json as _json
|
|
|
|
|
|
class LlmError(Exception):
|
|
"""Ошибка работы с LLM API."""
|
|
|
|
def __init__(self, message: str, code: str = 'llm_error', status: int | None = None):
|
|
super().__init__(message)
|
|
self.code = code
|
|
self.status = status
|
|
|
|
|
|
@dataclass
|
|
class LlmConfig:
|
|
provider: str
|
|
api_key: str
|
|
base_url: str
|
|
model: str
|
|
|
|
|
|
def get_llm_config() -> Optional[LlmConfig]:
|
|
if k := os.environ.get('DEEPSEEK_API_KEY'):
|
|
return LlmConfig(
|
|
provider='deepseek',
|
|
api_key=k,
|
|
base_url=(os.environ.get('LLM_BASE_URL') or 'https://api.deepseek.com/v1').rstrip('/'),
|
|
model=os.environ.get('LLM_MODEL') or 'deepseek-chat',
|
|
)
|
|
if k := os.environ.get('OPENAI_API_KEY'):
|
|
return LlmConfig(
|
|
provider='openai',
|
|
api_key=k,
|
|
base_url=(os.environ.get('LLM_BASE_URL') or 'https://api.openai.com/v1').rstrip('/'),
|
|
model=os.environ.get('LLM_MODEL') or 'gpt-4o-mini',
|
|
)
|
|
return None
|
|
|
|
|
|
def chat_completion_text_content(
|
|
cfg: LlmConfig,
|
|
system: str,
|
|
user: str,
|
|
temperature: float = 0.25,
|
|
timeout: int = 120,
|
|
) -> str:
|
|
"""Возвращает `assistant.message.content` (строку)."""
|
|
body: dict = {
|
|
'model': cfg.model,
|
|
'messages': [
|
|
{'role': 'system', 'content': system},
|
|
{'role': 'user', 'content': user},
|
|
],
|
|
'temperature': temperature,
|
|
}
|
|
if (os.environ.get('LLM_NO_JSON') or '').strip() != '1':
|
|
body['response_format'] = {'type': 'json_object'}
|
|
|
|
req = urllib.request.Request(
|
|
f'{cfg.base_url}/chat/completions',
|
|
data=_json.dumps(body).encode('utf-8'),
|
|
headers={
|
|
'Content-Type': 'application/json',
|
|
'Authorization': f'Bearer {cfg.api_key}',
|
|
},
|
|
method='POST',
|
|
)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
data = _json.loads(resp.read().decode('utf-8'))
|
|
except urllib.error.HTTPError as e:
|
|
text = ''
|
|
try:
|
|
text = e.read().decode('utf-8', errors='replace')
|
|
except Exception:
|
|
pass
|
|
raise LlmError(
|
|
f'LLM {e.code}: {(text or "").replace(chr(10), " ")[:280]}',
|
|
code='llm_http',
|
|
status=e.code,
|
|
)
|
|
except (urllib.error.URLError, TimeoutError) as e:
|
|
msg = str(getattr(e, 'reason', '') or e)
|
|
if 'timed out' in msg.lower():
|
|
raise LlmError('Превышен таймаут ожидания ответа LLM (120 с).', code='llm_timeout')
|
|
raise LlmError(f'Сбой сети при обращении к LLM: {msg}', code='llm_network')
|
|
|
|
try:
|
|
content = data['choices'][0]['message']['content']
|
|
except (KeyError, IndexError, TypeError):
|
|
content = None
|
|
if not isinstance(content, str) or not content.strip():
|
|
raise LlmError('Пустой content в ответе API.', code='llm_empty')
|
|
return content
|
|
|
|
|
|
def ping_llm(timeout: int = 30) -> dict:
|
|
"""Smoke-проверка подключения к LLM. Не бросает исключений — всё в результате.
|
|
|
|
Возвращает: {'ok': bool, 'provider', 'model', 'error'?, 'latencyMs'?, 'sample'?}
|
|
"""
|
|
import time
|
|
|
|
cfg = get_llm_config()
|
|
if cfg is None:
|
|
return {
|
|
'ok': False,
|
|
'configured': False,
|
|
'error': 'Ключ не задан. Задайте DEEPSEEK_API_KEY или OPENAI_API_KEY в .env.',
|
|
}
|
|
started = time.monotonic()
|
|
try:
|
|
raw = chat_completion_text_content(
|
|
cfg,
|
|
'Отвечай ТОЛЬКО JSON: {"ok": true}.',
|
|
'ping',
|
|
temperature=0.0,
|
|
timeout=timeout,
|
|
)
|
|
ms = int((time.monotonic() - started) * 1000)
|
|
return {
|
|
'ok': True,
|
|
'configured': True,
|
|
'provider': cfg.provider,
|
|
'model': cfg.model,
|
|
'latencyMs': ms,
|
|
'sample': raw[:120],
|
|
}
|
|
except LlmError as e:
|
|
ms = int((time.monotonic() - started) * 1000)
|
|
return {
|
|
'ok': False,
|
|
'configured': True,
|
|
'provider': cfg.provider,
|
|
'model': cfg.model,
|
|
'latencyMs': ms,
|
|
'error': str(e),
|
|
'code': e.code,
|
|
}
|
|
except Exception as e:
|
|
return {
|
|
'ok': False,
|
|
'configured': True,
|
|
'provider': cfg.provider,
|
|
'model': cfg.model,
|
|
'error': f'{type(e).__name__}: {e}',
|
|
'code': 'unknown',
|
|
}
|