The open-source AI voice studio. Clone, dictate, create.
Add custom OpenAI-compatible LLM endpoint
Moroya Sakamoto791be163bbce
diff --git a/backend/app.py b/backend/app.pyindex 3d892e3c..0c1de33e 100644--- a/backend/app.py+++ b/backend/app.py@@ -312,6 +312,20 @@ async def _run_startup(application: FastAPI) -> None:finally:db.close()+ # Seed the LLM backend dispatch from the persisted capture settings so+ # the very first refinement / personality call after startup honours a+ # user-configured custom OpenAI-compatible endpoint without needing a+ # settings-write to flip the module state first.+ db = next(get_db())+ try:+ from .services.settings import bootstrap_llm_backend_config++ bootstrap_llm_backend_config(db)+ except Exception as e:+ logger.warning("Could not bootstrap custom LLM config: %s", e)+ finally:+ db.close()+backend_type = get_backend_type()logger.info("Backend: %s", backend_type.upper())logger.info("GPU: %s", _get_gpu_status())diff --git a/backend/backends/__init__.py b/backend/backends/__init__.pyindex 4da1a439..0c8c8187 100644--- a/backend/backends/__init__.py+++ b/backend/backends/__init__.py@@ -214,6 +214,14 @@ _stt_backend: Optional[STTBackend] = None_llm_backends: dict[str, LLMBackend] = {}_llm_backends_lock = threading.Lock()+# Custom OpenAI-compatible LLM endpoint config, seeded from persisted+# capture settings on startup and refreshed whenever the settings service+# writes an update. Empty strings and None both mean "unset" and fall back+# to the built-in Qwen3 backend.+_custom_llm_endpoint: Optional[str] = None+_custom_llm_model: Optional[str] = None+_custom_llm_api_key: Optional[str] = None+# Supported TTS engines — keyed by engine name, value is the backend class import path.# The factory function uses this for the if/elif chain; the model configs live on the backend classes.TTS_ENGINES = {@@ -789,11 +797,72 @@ def get_stt_backend() -> STTBackend:return _stt_backend+def set_llm_config(+ endpoint: Optional[str],+ model: Optional[str],+ api_key: Optional[str],+) -> None:+ """Update the runtime custom-LLM endpoint config.++ Called from the settings service whenever the user writes to the+ ``custom_llm_endpoint`` / ``custom_llm_model`` / ``custom_llm_api_key``+ fields, and once on startup with the persisted row. Passing empty+ strings or ``None`` clears the config and reverts subsequent+ ``get_llm_backend()`` calls to the built-in Qwen3 path.++ A change drops any cached OpenAI-compat backend so the next call+ rebuilds against the new URL / model rather than reusing a stale one.+ """+ global _custom_llm_endpoint, _custom_llm_model, _custom_llm_api_key+ endpoint = endpoint or None+ model = model or None+ api_key = api_key or None+ changed = (+ endpoint != _custom_llm_endpoint+ or model != _custom_llm_model+ or api_key != _custom_llm_api_key+ )+ _custom_llm_endpoint = endpoint+ _custom_llm_model = model+ _custom_llm_api_key = api_key+ if changed:+ with _llm_backends_lock:+ _llm_backends.pop("openai_compat", None)++def get_llm_backend() -> LLMBackend:- """Get or create the default Qwen3 LLM backend based on platform."""+ """Get or create the active LLM backend.++ When a custom OpenAI-compatible endpoint has been configured via+ ``set_llm_config()``, returns an ``OpenAICompatLLMBackend`` targeting+ that endpoint; otherwise falls back to the platform-specific Qwen3+ backend (MLX on Apple Silicon, PyTorch elsewhere).+ """+ if _custom_llm_endpoint and _custom_llm_model:+ return _get_openai_compat_backend()return get_llm_backend_for_engine("qwen_llm")+def _get_openai_compat_backend() -> LLMBackend:+ """Return the cached OpenAI-compat backend, creating it on first call."""+ cached = _llm_backends.get("openai_compat")+ if cached is not None:+ return cached+ with _llm_backends_lock:+ cached = _llm_backends.get("openai_compat")+ if cached is not None:+ return cached+ from .openai_compat_backend import OpenAICompatLLMBackend++ backend = OpenAICompatLLMBackend(+ endpoint=_custom_llm_endpoint,+ model=_custom_llm_model,+ api_key=_custom_llm_api_key,+ )+ _llm_backends["openai_compat"] = backend+ return backend++def get_llm_backend_for_engine(engine: str) -> LLMBackend:"""Get or create an LLM backend for the given engine."""global _llm_backends@@ -825,7 +894,11 @@ def get_llm_backend_for_engine(engine: str) -> LLMBackend:def reset_backends():"""Reset backend instances (useful for testing)."""global _tts_backend, _tts_backends, _stt_backend, _llm_backends+ global _custom_llm_endpoint, _custom_llm_model, _custom_llm_api_key_tts_backend = None_tts_backends.clear()_stt_backend = None_llm_backends.clear()+ _custom_llm_endpoint = None+ _custom_llm_model = None+ _custom_llm_api_key = Nonediff --git a/backend/backends/openai_compat_backend.py b/backend/backends/openai_compat_backend.pynew file mode 100644index 00000000..2611878c--- /dev/null+++ b/backend/backends/openai_compat_backend.py@@ -0,0 +1,141 @@+"""+OpenAI-compatible LLM backend.++Delegates chat completion to any HTTP endpoint that speaks the OpenAI+``/v1/chat/completions`` protocol — llama.cpp server, vLLM, LocalAI,+LM Studio, Ollama's OpenAI-compat shim, or the OpenAI API itself.+Skips the on-device download / model-load path because the remote+server is expected to serve the model.++The user configures ``custom_llm_endpoint`` / ``custom_llm_model`` /+``custom_llm_api_key`` in capture settings; when the endpoint is set,+``get_llm_backend()`` returns an instance of this class instead of the+built-in Qwen3 backend.+"""++import logging+from typing import Optional++import httpx++from . import DEFAULT_LLM_MAX_TOKENS, DEFAULT_LLM_TEMPERATURE++logger = logging.getLogger(__name__)++DEFAULT_REQUEST_TIMEOUT_SECONDS = 120.0+++class OpenAICompatLLMBackend:+ """LLM backend that delegates to an OpenAI-compatible chat endpoint."""++ def __init__(+ self,+ endpoint: str,+ model: str,+ api_key: Optional[str] = None,+ timeout: float = DEFAULT_REQUEST_TIMEOUT_SECONDS,+ ):+ # Strip a trailing slash so callers can pass either+ # ``http://host:port/v1`` or ``http://host:port/v1/``.+ self.endpoint = endpoint.rstrip("/")+ self.model = model+ # Empty string means "no auth" — the app UI stores an empty field+ # the same way an unset field looks in the DB.+ self.api_key = api_key or None+ self.timeout = timeout+ # ``model_size`` / ``_current_model_size`` are read by the shared+ # download-progress / unload plumbing on other backends. Report the+ # remote model name so the routes layer can echo it back to clients.+ self.model_size = model+ self._current_model_size = model++ def is_loaded(self) -> bool:+ # A remote endpoint is always "loaded" from this process's point of+ # view — no local weights to page in.+ return True++ async def load_model(self, model_size: Optional[str] = None) -> None: # noqa: ARG002+ """No-op — remote endpoint holds the model."""+ return++ def unload_model(self) -> None:+ """No-op — nothing to unload locally."""+ return++ async def generate(+ self,+ prompt: str,+ system: Optional[str] = None,+ max_tokens: int = DEFAULT_LLM_MAX_TOKENS,+ temperature: float = DEFAULT_LLM_TEMPERATURE,+ model_size: Optional[str] = None, # noqa: ARG002 — kept for protocol parity+ examples: Optional[list[tuple[str, str]]] = None,+ ) -> str:+ messages = _build_messages(prompt, system, examples)+ payload = {+ "model": self.model,+ "messages": messages,+ "max_tokens": max_tokens,+ "temperature": temperature,+ "stream": False,+ }+ headers = {"Content-Type": "application/json"}+ if self.api_key:+ headers["Authorization"] = f"Bearer {self.api_key}"++ url = f"{self.endpoint}/chat/completions"+ async with httpx.AsyncClient(timeout=self.timeout) as client:+ try:+ response = await client.post(url, headers=headers, json=payload)+ response.raise_for_status()+ except httpx.HTTPStatusError as exc:+ # Truncate the body — some servers echo the whole prompt in+ # error responses, and log files fill up fast otherwise.+ body_preview = exc.response.text[:500]+ logger.error(+ "OpenAI-compat endpoint %s returned %d: %s",+ url,+ exc.response.status_code,+ body_preview,+ )+ raise+ except httpx.RequestError as exc:+ logger.error("OpenAI-compat endpoint %s request failed: %s", url, exc)+ raise++ data = response.json()++ return _extract_content(data, url)+++def _build_messages(+ prompt: str,+ system: Optional[str],+ examples: Optional[list[tuple[str, str]]],+) -> list[dict]:+ messages: list[dict] = []+ if system:+ messages.append({"role": "system", "content": system})+ if examples:+ for user_text, assistant_text in examples:+ messages.append({"role": "user", "content": user_text})+ messages.append({"role": "assistant", "content": assistant_text})+ messages.append({"role": "user", "content": prompt})+ return messages+++def _extract_content(data: dict, url: str) -> str:+ choices = data.get("choices") or []+ if not choices:+ raise ValueError(f"No choices in response from {url}: {data!r}")++ first = choices[0]+ message = first.get("message") or {}+ content = message.get("content")+ if content is None:+ # Fallback: some servers still return the legacy text-completion+ # shape (``choices[0].text``) even from the chat endpoint.+ content = first.get("text")+ if content is None:+ raise ValueError(f"No content in response from {url}: {data!r}")+ return content.strip()diff --git a/backend/database/migrations.py b/backend/database/migrations.pyindex a4de4379..bb75510b 100644--- a/backend/database/migrations.py+++ b/backend/database/migrations.py@@ -244,6 +244,27 @@ def _migrate_capture_settings(engine, inspector, tables: set[str]) -> None:"hotkey_enabled BOOLEAN NOT NULL DEFAULT 0","hotkey_enabled",)+ if "custom_llm_endpoint" not in columns:+ _add_column(+ engine,+ "capture_settings",+ "custom_llm_endpoint VARCHAR",+ "custom_llm_endpoint",+ )+ if "custom_llm_model" not in columns:+ _add_column(+ engine,+ "capture_settings",+ "custom_llm_model VARCHAR",+ "custom_llm_model",+ )+ if "custom_llm_api_key" not in columns:+ _add_column(+ engine,+ "capture_settings",+ "custom_llm_api_key VARCHAR",+ "custom_llm_api_key",+ )def _migrate_mcp_bindings(engine, inspector, tables: set[str]) -> None:diff --git a/backend/database/models.py b/backend/database/models.pyindex 3462ba0c..04133f19 100644--- a/backend/database/models.py+++ b/backend/database/models.py@@ -218,6 +218,14 @@ class CaptureSettings(Base):chord_toggle_to_talk_keys = Column(JSON, nullable=False, default=default_toggle_to_talk_chord)+ # Optional OpenAI-compatible endpoint that overrides the built-in Qwen3+ # LLM for refinement / personality rewriting. When ``custom_llm_endpoint``+ # is set, the backend layer delegates every LLM call to this URL instead+ # of running Qwen locally; leaving it null keeps the on-device path and+ # the ``llm_model`` size selector above.+ custom_llm_endpoint = Column(String, nullable=True)+ custom_llm_model = Column(String, nullable=True)+ custom_llm_api_key = Column(String, nullable=True)updated_at = Column(DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC))diff --git a/backend/models.py b/backend/models.pyindex 94a9fd54..fd7bbbc4 100644--- a/backend/models.py+++ b/backend/models.py@@ -264,6 +264,9 @@ class CaptureSettingsResponse(BaseModel):chord_toggle_to_talk_keys: List[str] = Field(default_factory=default_toggle_to_talk_chord)+ custom_llm_endpoint: Optional[str] = None+ custom_llm_model: Optional[str] = None+ custom_llm_api_key: Optional[str] = Noneclass Config:from_attributes = True@@ -284,6 +287,9 @@ class CaptureSettingsUpdate(BaseModel):hotkey_enabled: Optional[bool] = Nonechord_push_to_talk_keys: Optional[List[str]] = Field(default=None, min_length=1, max_length=6)chord_toggle_to_talk_keys: Optional[List[str]] = Field(default=None, min_length=1, max_length=6)+ custom_llm_endpoint: Optional[str] = None+ custom_llm_model: Optional[str] = None+ custom_llm_api_key: Optional[str] = Noneclass GenerationSettingsResponse(BaseModel):diff --git a/backend/routes/llm.py b/backend/routes/llm.pyindex 0b394dcf..49c4bd88 100644--- a/backend/routes/llm.py+++ b/backend/routes/llm.py@@ -18,40 +18,54 @@ router = APIRouter()@router.post("/llm/generate", response_model=models.LLMGenerateResponse)async def llm_generate(request: models.LLMGenerateRequest):- """Run a single-turn Qwen3 completion."""+ """Run a single-turn chat completion via the active LLM backend.++ Routes to the built-in Qwen3 backend by default. If the user has+ configured a custom OpenAI-compatible endpoint under capture settings,+ ``get_llm_model()`` returns that backend and the Qwen-specific size+ validation / download-progress plumbing below is skipped.+ """+ from ..backends.openai_compat_backend import OpenAICompatLLMBackend+backend = llm.get_llm_model()- model_size = request.model_size or backend.model_size- valid_sizes = {cfg.model_size for cfg in get_llm_model_configs()}- if model_size not in valid_sizes:- raise HTTPException(- status_code=400,- detail=f"Invalid LLM size '{model_size}'. Must be one of: {sorted(valid_sizes)}",- )+ if isinstance(backend, OpenAICompatLLMBackend):+ # Custom endpoint owns model selection. The remote server validates+ # its own model name and there's nothing to download locally.+ model_size = backend.model_size+ else:+ model_size = request.model_size or backend.model_size- already_loaded = backend.is_loaded() and backend.model_size == model_size- if not already_loaded and not backend._is_model_cached(model_size):- progress_model_name = f"qwen3-{model_size.lower()}"- task_manager = get_task_manager()-- async def download_llm_background():- try:- await backend.load_model(model_size)- task_manager.complete_download(progress_model_name)- except Exception as e:- task_manager.error_download(progress_model_name, str(e))-- task_manager.start_download(progress_model_name)- create_background_task(download_llm_background())-- return JSONResponse(- status_code=202,- content={- "message": f"Qwen3 {model_size} is being downloaded. Please wait and try again.",- "model_name": progress_model_name,- "downloading": True,- },- )+ valid_sizes = {cfg.model_size for cfg in get_llm_model_configs()}+ if model_size not in valid_sizes:+ raise HTTPException(+ status_code=400,+ detail=f"Invalid LLM size '{model_size}'. Must be one of: {sorted(valid_sizes)}",+ )++ already_loaded = backend.is_loaded() and backend.model_size == model_size+ if not already_loaded and not backend._is_model_cached(model_size):+ progress_model_name = f"qwen3-{model_size.lower()}"+ task_manager = get_task_manager()++ async def download_llm_background():+ try:+ await backend.load_model(model_size)+ task_manager.complete_download(progress_model_name)+ except Exception as e:+ task_manager.error_download(progress_model_name, str(e))++ task_manager.start_download(progress_model_name)+ create_background_task(download_llm_background())++ return JSONResponse(+ status_code=202,+ content={+ "message": f"Qwen3 {model_size} is being downloaded. Please wait and try again.",+ "model_name": progress_model_name,+ "downloading": True,+ },+ )examples: list[tuple[str, str]] | None = Noneif request.examples:diff --git a/backend/services/settings.py b/backend/services/settings.pyindex 31e3bf96..fd9cc04a 100644--- a/backend/services/settings.py+++ b/backend/services/settings.py@@ -74,9 +74,36 @@ def update_capture_settings(db: Session, patch: dict[str, Any]) -> DBCaptureSett_apply_patch(row, patch)db.commit()db.refresh(row)+ _sync_llm_backend_config(row)return row+def _sync_llm_backend_config(row: DBCaptureSettings) -> None:+ """Push the persisted custom-LLM endpoint into the backend module state.++ Called after every capture-settings write and once on startup from+ ``bootstrap_llm_backend_config``. Keeps the runtime dispatch in+ ``backends.get_llm_backend()`` in sync with what the DB row holds so+ the user's next refinement / personality call routes to the new URL+ without a restart.+ """+ # Imported inline to avoid a circular import at module load — the+ # backends package pulls in HF patches that in turn import services.+ from .. import backends++ backends.set_llm_config(+ endpoint=row.custom_llm_endpoint,+ model=row.custom_llm_model,+ api_key=row.custom_llm_api_key,+ )+++def bootstrap_llm_backend_config(db: Session) -> None:+ """Seed the backend LLM config from the persisted row on server startup."""+ row = _get_or_create_capture_row(db)+ _sync_llm_backend_config(row)++def get_generation_settings(db: Session) -> DBGenerationSettings:"""Return the generation settings row, creating it with defaults if missing."""return _get_or_create_generation_row(db)