Skip to content

The agent that grows with you

refactor(web): collapse try/except-HTTPException/log/raise boilerplate into _common.http_failure; trim unused fastapi imports

Tekniumba4f4b8161e8
diff --git a/hermes_cli/web_routers/_common.py b/hermes_cli/web_routers/_common.py
index faea6c71896..15eba005bad 100644
--- a/hermes_cli/web_routers/_common.py
+++ b/hermes_cli/web_routers/_common.py
@@ -48,11 +48,14 @@ async def scoped_to_thread(profile: Optional[str], fn: Callable[[], Any]) -> Any
@contextlib.contextmanager
-def http_failure(log_msg: str, status: int, prefix: str):
- """Map unexpected exceptions to ``HTTPException(status, f"{prefix}: {exc}")``.
+def http_failure(log_msg: str, status: int, prefix: Optional[str] = None, *, detail: Optional[str] = None):
+ """Map unexpected exceptions to an ``HTTPException``.
``HTTPException`` passes through untouched; anything else is logged with
- ``log_msg`` (full traceback) first.
+ ``log_msg`` (full traceback) first, then re-raised as
+ ``HTTPException(status, f"{prefix}: {exc}")`` or — when ``detail`` is
+ given instead — ``HTTPException(status, detail)`` (fixed message, the
+ exception text is only in the log).
"""
try:
yield
@@ -60,7 +63,7 @@ def http_failure(log_msg: str, status: int, prefix: str):
raise
except Exception as exc:
log.exception(log_msg)
- raise HTTPException(status_code=status, detail=f"{prefix}: {exc}")
+ raise HTTPException(status_code=status, detail=detail if detail is not None else f"{prefix}: {exc}")
def spawn_profile_action(
diff --git a/hermes_cli/web_routers/actions.py b/hermes_cli/web_routers/actions.py
index b3aa17c6ce8..29f30959416 100644
--- a/hermes_cli/web_routers/actions.py
+++ b/hermes_cli/web_routers/actions.py
@@ -9,6 +9,7 @@ import asyncio
import secrets
import subprocess
from fastapi import APIRouter
+from hermes_cli.web_routers._common import http_failure
from hermes_cli.web_deps import late
from fastapi import HTTPException, Request
from hermes_cli import __version__
@@ -33,13 +34,8 @@ get_hermes_home = late("get_hermes_home")
@router.post("/api/gateway/restart")
async def restart_gateway(profile: Optional[str] = None):
"""Kick off a ``hermes gateway restart`` in the background."""
- try:
+ with http_failure("Failed to spawn gateway restart", 500, "Failed to restart gateway"):
proc, _reused = _spawn_gateway_restart(profile)
- except HTTPException:
- raise
- except Exception as exc:
- _log.exception("Failed to spawn gateway restart")
- raise HTTPException(status_code=500, detail=f"Failed to restart gateway: {exc}")
return {
"ok": True,
"pid": proc.pid,
diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.py
index bb5ff5ee7fd..59735d9fb0b 100644
--- a/hermes_cli/web_routers/audio.py
+++ b/hermes_cli/web_routers/audio.py
@@ -17,6 +17,7 @@ import os
import urllib.parse
import urllib.request
from fastapi import APIRouter
+from hermes_cli.web_routers._common import http_failure
from hermes_cli.web_deps import late
from fastapi import HTTPException, WebSocket, WebSocketDisconnect
from hermes_cli.web_models import AudioTranscriptionRequest, TTSSpeakRequest, TTSLeaseRequest
@@ -270,7 +271,9 @@ async def speak_text(payload: TTSSpeakRequest, profile: Optional[str] = None):
if not text:
raise HTTPException(status_code=400, detail="Text is required")
- try:
+ # _config_profile_scope raises 400/404 for a bad profile — pass it
+ # through instead of masking it as a 500 synthesis failure.
+ with http_failure("Desktop voice TTS failed", 500, "Speech synthesis failed"):
from tools.tts_tool import text_to_speech_tool
def _speak_scoped():
@@ -283,13 +286,6 @@ async def speak_text(payload: TTSSpeakRequest, profile: Optional[str] = None):
loop = asyncio.get_running_loop()
result_json = await loop.run_in_executor(None, _speak_scoped)
- except HTTPException:
- # _config_profile_scope raises 400/404 for a bad profile — pass it
- # through instead of masking it as a 500 synthesis failure.
- raise
- except Exception as exc:
- _log.exception("Desktop voice TTS failed")
- raise HTTPException(status_code=500, detail=f"Speech synthesis failed: {exc}")
try:
result = json.loads(result_json) if isinstance(result_json, str) else result_json
diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.py
index da35621d46d..620f74ece64 100644
--- a/hermes_cli/web_routers/config_env.py
+++ b/hermes_cli/web_routers/config_env.py
@@ -10,6 +10,7 @@ import asyncio
import time
import urllib.parse
from fastapi import APIRouter
+from hermes_cli.web_routers._common import http_failure
from hermes_cli.web_deps import late
from fastapi import HTTPException, Request
from hermes_cli.config import DEFAULT_CONFIG, OPTIONAL_ENV_VARS, read_raw_config, custom_endpoint_key_env, coerce_provider_id, find_provider_entry, redact_key, _deep_merge
@@ -114,13 +115,8 @@ async def update_config(body: ConfigUpdate, profile: Optional[str] = None):
_broadcast_gateway_session_info()
return {"ok": True}
- try:
+ with http_failure("PUT /api/config failed", 500, detail="Internal server error"):
return await asyncio.to_thread(_run)
- except HTTPException:
- raise
- except Exception:
- _log.exception("PUT /api/config failed")
- raise HTTPException(status_code=500, detail="Internal server error")
def _catalog_provider_env_metadata() -> dict:
@@ -576,20 +572,15 @@ def list_custom_endpoints(profile: Optional[str] = None):
active profile, so read/write must resolve that profile's home rather than
the process-level HERMES_HOME. Mirrors ``/api/config``'s profile scoping.
"""
- try:
+ with http_failure("GET /api/providers/custom-endpoints failed", 500, detail="Failed to list custom endpoints"):
with _config_profile_scope(profile):
return _custom_endpoint_response(load_config())
- except HTTPException:
- raise
- except Exception:
- _log.exception("GET /api/providers/custom-endpoints failed")
- raise HTTPException(status_code=500, detail="Failed to list custom endpoints")
@router.post("/api/providers/custom-endpoints")
def upsert_custom_endpoint(body: CustomEndpointUpdate, profile: Optional[str] = None):
"""Create or update a v12+ ``providers`` custom endpoint entry."""
- try:
+ with http_failure("POST /api/providers/custom-endpoints failed", 500, detail="Failed to save custom endpoint"):
with _config_profile_scope(profile):
cfg = load_config()
endpoint_id, _entry = _write_custom_endpoint(cfg, body)
@@ -598,11 +589,6 @@ def upsert_custom_endpoint(body: CustomEndpointUpdate, profile: Optional[str] =
response["ok"] = True
response["id"] = endpoint_id
return response
- except HTTPException:
- raise
- except Exception:
- _log.exception("POST /api/providers/custom-endpoints failed")
- raise HTTPException(status_code=500, detail="Failed to save custom endpoint")
@router.post("/api/providers/custom-endpoints/{endpoint_id}/activate")
diff --git a/hermes_cli/web_routers/models.py b/hermes_cli/web_routers/models.py
index 2e3338c2d66..77b4f13f571 100644
--- a/hermes_cli/web_routers/models.py
+++ b/hermes_cli/web_routers/models.py
@@ -7,6 +7,7 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o
import logging
import asyncio
from fastapi import APIRouter
+from hermes_cli.web_routers._common import http_failure
from hermes_cli.web_deps import late
from fastapi import HTTPException
from hermes_cli.web_models import ModelAssignment, MoaModelSlot, MoaPresetPayload, MoaConfigPayload
@@ -130,7 +131,7 @@ async def get_model_options(
re-fetches its live catalog — used by the picker's explicit "Refresh
Models" control. Normal opens leave it false to stay on the 1h cache.
"""
- try:
+ with http_failure("GET /api/model/options failed", 500, detail="Failed to list model options"):
skew_msg = _dashboard_code_skew_guard()
if skew_msg:
_log.warning("GET /api/model/options refused: %s", skew_msg)
@@ -157,11 +158,6 @@ async def get_model_options(
)
return await run_in_threadpool(_build_payload_scoped)
- except HTTPException:
- raise
- except Exception:
- _log.exception("GET /api/model/options failed")
- raise HTTPException(status_code=500, detail="Failed to list model options")
@router.get("/api/model/recommended-default")
@@ -273,7 +269,7 @@ def get_auxiliary_models(profile: Optional[str] = None):
selected profile's (read/write asymmetry).
"""
from hermes_cli.web_server import _AUX_TASK_SLOTS
- try:
+ with http_failure("GET /api/model/auxiliary failed", 500, detail="Failed to read auxiliary config"):
with _profile_scope(profile):
cfg = load_config()
aux_cfg = cfg.get("auxiliary", {})
@@ -300,33 +296,23 @@ def get_auxiliary_models(profile: Optional[str] = None):
main = {"provider": "", "model": str(model_cfg) if model_cfg else ""}
return {"tasks": tasks, "main": main}
- except HTTPException:
- raise
- except Exception:
- _log.exception("GET /api/model/auxiliary failed")
- raise HTTPException(status_code=500, detail="Failed to read auxiliary config")
@router.get("/api/model/moa")
def get_moa_models(profile: Optional[str] = None):
"""Return the configured Mixture-of-Agents provider/model slots."""
- try:
+ with http_failure("GET /api/model/moa failed", 500, detail="Failed to read MoA config"):
from hermes_cli.moa_config import normalize_moa_config
with _profile_scope(profile):
cfg = load_config()
return normalize_moa_config(cfg.get("moa") if isinstance(cfg, dict) else {})
- except HTTPException:
- raise
- except Exception:
- _log.exception("GET /api/model/moa failed")
- raise HTTPException(status_code=500, detail="Failed to read MoA config")
@router.put("/api/model/moa")
def set_moa_models(body: MoaConfigPayload, profile: Optional[str] = None):
"""Persist the Mixture-of-Agents provider/model slots."""
- try:
+ with http_failure("PUT /api/model/moa failed", 500, detail="Failed to save MoA config"):
from hermes_cli.moa_config import normalize_moa_config, validate_moa_payload
def _slot_dict(slot: MoaModelSlot) -> dict:
@@ -390,11 +376,6 @@ def set_moa_models(body: MoaConfigPayload, profile: Optional[str] = None):
cfg.setdefault("moa", {}).update(normalized)
save_config(cfg)
return {"ok": True, **normalized}
- except HTTPException:
- raise
- except Exception:
- _log.exception("PUT /api/model/moa failed")
- raise HTTPException(status_code=500, detail="Failed to save MoA config")
@router.post("/api/model/set")
@@ -415,7 +396,7 @@ async def set_model_assignment(body: ModelAssignment, profile: Optional[str] = N
if scope not in {"main", "auxiliary"}:
raise HTTPException(status_code=400, detail="scope must be 'main' or 'auxiliary'")
- try:
+ with http_failure("POST /api/model/set failed", 500, detail="Failed to save model assignment"):
# Expensive-model warning runs BEFORE the profile scope is entered:
# _profile_scope must never be held across an await (the RLock is
# reentrant per-thread, so a second coroutine interleaving on the
@@ -451,8 +432,3 @@ async def set_model_assignment(body: ModelAssignment, profile: Optional[str] = N
)
return await asyncio.to_thread(_apply_assignment)
- except HTTPException:
- raise
- except Exception:
- _log.exception("POST /api/model/set failed")
- raise HTTPException(status_code=500, detail="Failed to save model assignment")
diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.py
index 46157f57e42..5f22be2aaa3 100644
--- a/hermes_cli/web_routers/ops.py
+++ b/hermes_cli/web_routers/ops.py
@@ -13,6 +13,7 @@ import os
import secrets
from datetime import datetime, timezone
from fastapi import APIRouter
+from hermes_cli.web_routers._common import http_failure
from hermes_cli.web_deps import late
from fastapi import File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse
@@ -301,25 +302,15 @@ async def set_webhook_enabled(name: str, body: WebhookEnabledToggle):
@router.post("/api/gateway/start")
async def start_gateway(profile: Optional[str] = None):
- try:
+ with http_failure("Failed to spawn gateway start", 500, "Failed to start gateway"):
proc = _spawn_hermes_action(_gateway_subcommand(profile, "start"), "gateway-start")
- except HTTPException:
- raise
- except Exception as exc:
- _log.exception("Failed to spawn gateway start")
- raise HTTPException(status_code=500, detail=f"Failed to start gateway: {exc}")
return {"ok": True, "pid": proc.pid, "name": "gateway-start"}
@router.post("/api/gateway/stop")
async def stop_gateway(profile: Optional[str] = None):
- try:
+ with http_failure("Failed to spawn gateway stop", 500, "Failed to stop gateway"):
proc = _spawn_hermes_action(_gateway_subcommand(profile, "stop"), "gateway-stop")
- except HTTPException:
- raise
- except Exception as exc:
- _log.exception("Failed to spawn gateway stop")
- raise HTTPException(status_code=500, detail=f"Failed to stop gateway: {exc}")
return {"ok": True, "pid": proc.pid, "name": "gateway-stop"}
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index 86f593c945d..738818f85df 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -27,7 +27,7 @@ from hermes_cli.web_models import (
SessionPrune,
SessionRename,
)
-from hermes_cli.web_routers._common import log as _log
+from hermes_cli.web_routers._common import log as _log, http_failure
from hermes_state import is_malformed_db_error, is_transient_sqlite_error
list_router = APIRouter()
@@ -230,7 +230,7 @@ async def search_sessions(
"""
if not q or not q.strip():
return {"results": []}
- try:
+ with http_failure("GET /api/sessions/search failed", 500, detail="Search failed"):
db = _open_session_db_for_profile(profile, read_only=True)
try:
safe_limit = max(1, min(int(limit or 20), 100))
@@ -416,11 +416,6 @@ async def search_sessions(
return {"results": list(seen.values())}
finally:
db.close()
- except HTTPException:
- raise
- except Exception:
- _log.exception("GET /api/sessions/search failed")
- raise HTTPException(status_code=500, detail="Search failed")
@manage_router.post("/api/sessions/bulk-delete")
@@ -654,15 +649,10 @@ async def backfill_session_owner_profiles(body: SessionOwnerBackfill):
"""
stamp = _serving_profile(body.profile)
- try:
+ with http_failure("POST /api/sessions/owner-backfill failed", 500, detail="Internal server error"):
stamped = await asyncio.to_thread(
_with_db, body.profile, lambda db: db.backfill_null_session_profiles(stamp), read_only=False
)
- except HTTPException:
- raise
- except Exception:
- _log.exception("POST /api/sessions/owner-backfill failed")
- raise HTTPException(status_code=500, detail="Internal server error")
if stamped:
_log.info(
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 707454498f1..215196b078c 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -88,14 +88,10 @@ from gateway.status import (
from utils import env_var_enabled
try:
- from fastapi import (
- FastAPI, File, Form, HTTPException, Query, Request, UploadFile,
- WebSocket, WebSocketDisconnect,
- )
+ from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
- from pydantic import BaseModel, SecretStr, field_validator
from starlette.concurrency import run_in_threadpool
except ImportError:
# First try lazy-installing the dashboard extras. Only the user actually