from __future__ import annotations import time from typing import Any import httpx from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from calliope.config import AGENT_LLM_ROLES, normalize_path, settings router = APIRouter() _LEGACY_LLM_KEYS = {"llm_base_url", "llm_model", "llm_api_key"} _LLM_TEST_TIMEOUT_SEC = 15.0 _LLM_TEST_TIMEOUT_RANGE = (5, 60) class LlmProfileIn(BaseModel): id: str | None = None name: str | None = None base_url: str | None = None model: str | None = None api_key: str | None = None class LlmTestIn(BaseModel): profile_id: str | None = None base_url: str | None = None model: str | None = None api_key: str | None = None # Probe timeout requested by the caller (models settings page dropdown). # Clamped server-side regardless of what the client sends. timeout_sec: float | None = Field( None, ge=_LLM_TEST_TIMEOUT_RANGE[0], le=_LLM_TEST_TIMEOUT_RANGE[1] ) class SettingsUpdate(BaseModel): llm_base_url: str | None = None llm_model: str | None = None llm_api_key: str | None = None llm_profiles: list[LlmProfileIn] | None = None llm_active_id: str | None = None agent_llm_assignments: dict[str, str | None] | None = None comfyui_base_url: str | None = None comfyui_active_id: str | None = None data_dir: str | None = None assets_dir: str | None = None agent_workspace_dir: str | None = None agent_shell_enabled: bool | None = None queue_concurrency: int | None = Field(None, ge=1, le=8) queue_poll_interval_sec: float | None = Field(None, ge=0.5, le=60.0) queue_poll_timeout_sec: float | None = Field(None, ge=0, le=86400.0) queue_max_retries: int | None = Field(None, ge=0, le=10) agent_max_steps: int | None = Field(None, ge=1, le=100) agent_hardening_prompt: str | None = Field(None, max_length=20000) agent_history_char_budget: int | None = Field(None, ge=10_000, le=2_000_000) h3_rewrite_extra_body: dict[str, Any] | None = None dry_run: bool | None = None @router.get("") async def get_settings() -> dict[str, Any]: return settings.to_public_dict() @router.post("") async def update_settings(payload: SettingsUpdate) -> dict[str, Any]: data = payload.model_dump(exclude_unset=True) profiles_in = data.pop("llm_profiles", None) active_in = data.pop("llm_active_id", None) assignments_in = data.pop("agent_llm_assignments", None) legacy_llm = {k: data.pop(k) for k in list(data) if k in _LEGACY_LLM_KEYS} active_comfy_in = data.pop("comfyui_active_id", None) legacy_comfy_url = data.pop("comfyui_base_url", None) for key, value in data.items(): if key in {"data_dir", "assets_dir", "agent_workspace_dir"}: path = normalize_path(value) if path is not None: setattr(settings, key, path) continue if key == "dry_run": setattr(settings, key, bool(value)) continue if key == "agent_shell_enabled": setattr(settings, key, bool(value)) continue setattr(settings, key, value) if profiles_in is not None: try: settings.replace_llm_profiles(profiles_in) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc if active_in is not None: settings.ensure_llm_profiles() ids = {p["id"] for p in settings.llm_profiles} if active_in not in ids: raise HTTPException(status_code=400, detail="Unknown LLM profile") settings.llm_active_id = active_in settings.apply_active_llm() if assignments_in is not None: settings.ensure_llm_profiles() ids = {p["id"] for p in settings.llm_profiles} # HEL-619: per-role INCREMENTAL update. Rapid dropdown switches used # to send whole cached snapshots that fully overwrote the map, so a # stale snapshot could wipe a newer choice. Roles absent from the # payload keep their stored value; a role sent as null is cleared. cleaned: dict[str, str | None] = dict(settings.agent_llm_assignments or {}) for role, pid in assignments_in.items(): if role not in AGENT_LLM_ROLES: continue if pid is not None and pid not in ids: raise HTTPException( status_code=400, detail=f"Unknown LLM profile for role: {role}", ) cleaned[role] = pid settings.agent_llm_assignments = cleaned if legacy_llm: for key, value in legacy_llm.items(): setattr(settings, key, value) settings.sync_legacy_llm_into_active() if active_comfy_in is not None: settings.ensure_comfyui_endpoints() ids = {ep["id"] for ep in settings.comfyui_endpoints} if active_comfy_in not in ids: raise HTTPException(status_code=400, detail="Unknown ComfyUI endpoint") settings.comfyui_active_id = active_comfy_in settings.apply_active_comfyui() if legacy_comfy_url is not None: # Legacy single-address PATCH (old Settings page): write it onto the # active endpoint so the two views never diverge (HEL-611). setattr(settings, "comfyui_base_url", legacy_comfy_url) settings.sync_legacy_comfyui_into_active() settings.save_config_file() return settings.to_public_dict() @router.post("/llm-test") async def test_llm_connection(payload: LlmTestIn) -> dict[str, Any]: settings.ensure_llm_profiles() base_url = (payload.base_url or "").strip() model = (payload.model or "").strip() api_key = (payload.api_key or "").strip() or None if payload.profile_id: profile = next( (p for p in settings.llm_profiles if p.get("id") == payload.profile_id), None ) if profile is None: raise HTTPException(status_code=404, detail="Unknown LLM profile") if not base_url: base_url = str(profile.get("base_url") or "").strip() if not model: model = str(profile.get("model") or "").strip() if api_key is None: key = profile.get("api_key") if isinstance(key, str) and key.strip(): api_key = key if not base_url or not model: raise HTTPException(status_code=400, detail="base_url and model are required") url = f"{base_url.rstrip('/')}/chat/completions" headers = {"Content-Type": "application/json"} if api_key: headers["Authorization"] = f"Bearer {api_key}" body = { "model": model, "messages": [{"role": "user", "content": "ping"}], "max_tokens": 1, "stream": False, "temperature": 0, } timeout_sec = payload.timeout_sec if payload.timeout_sec is not None else _LLM_TEST_TIMEOUT_SEC timeout_sec = min( max(timeout_sec, _LLM_TEST_TIMEOUT_RANGE[0]), _LLM_TEST_TIMEOUT_RANGE[1], ) started = time.perf_counter() try: async with httpx.AsyncClient(timeout=timeout_sec) as client: resp = await client.post(url, headers=headers, json=body) except httpx.TimeoutException: return { "ok": False, "error": "timeout", "detail": f"no response within {timeout_sec:.0f}s", "timeout_sec": timeout_sec, } except httpx.HTTPError as exc: return {"ok": False, "error": "connect", "detail": str(exc) or exc.__class__.__name__} elapsed_ms = int((time.perf_counter() - started) * 1000) if resp.status_code in (401, 403): return {"ok": False, "error": "auth", "detail": f"HTTP {resp.status_code}"} if resp.status_code == 404: return { "ok": False, "error": "not_found", "detail": "HTTP 404 — check base URL (OpenAI-compatible servers usually end with /v1)", } if resp.status_code >= 400: text = resp.text[:200].strip().replace("\n", " ") return {"ok": False, "error": "http", "detail": f"HTTP {resp.status_code}: {text}"} try: data = resp.json() except ValueError: return {"ok": False, "error": "http", "detail": "response is not JSON"} if not (isinstance(data, dict) and data.get("choices")): return {"ok": False, "error": "http", "detail": "response has no choices"} return {"ok": True, "elapsed_ms": elapsed_ms}