Repository navigation
Add custom OpenAI-compatible LLM endpoint for refinement and personality - #1167
Merged
Merged
Conversation
Adds a backend that delegates chat completions to any HTTP endpoint speaking the OpenAI /v1/chat/completions protocol -- llama.cpp server, vLLM, LM Studio, LocalAI, Ollama's shim, or the OpenAI API itself. Bypasses the on-device Qwen download / load path so the remote model serves every refinement / personality call. - New OpenAICompatLLMBackend implementing the LLMBackend protocol. Non-streaming for now; a streaming variant can layer on top of the same request builder. - Module-level custom-LLM config with set_llm_config() plus a get_llm_backend() dispatch that reroutes to the remote backend when the endpoint is configured. Config changes drop the cached backend so URL / model swaps take effect immediately without a restart. - Three new capture_settings columns (custom_llm_endpoint, custom_llm_model, custom_llm_api_key) with an idempotent column-add migration and matching CaptureSettingsResponse / CaptureSettingsUpdate fields. - Startup bootstrap seeds set_llm_config() from the persisted row before the first LLM call; every capture-settings PUT re-syncs. - /llm/generate route skips the Qwen size validation and download- progress branch when the custom endpoint is active (remote server owns model selection). UI wiring in ProfileForm / capture-settings pane is a follow-up; the backend is already reachable through the existing PUT /settings/captures endpoint.
Real HTTP round-trip against a caller-configured endpoint -- no mocks -- covering protocol compliance, few-shot history propagation, dispatch, config-change cache invalidation, and fallback to the built-in Qwen path when the endpoint is cleared. Skips automatically when VOICEBOX_TEST_OPENAI_COMPAT_URL and VOICEBOX_TEST_OPENAI_COMPAT_MODEL are unset or the endpoint is not listening, so `pytest` on a fresh clone still returns green. The docstring at the top of the file documents the workflow for pointing it at llama.cpp, vLLM, LM Studio, Ollama, or OpenAI itself.
Adds three fields to the CaptureSettings TypeScript interface matching the backend Pydantic schema, and a "Custom LLM endpoint (advanced)" section under the Refinement group on the Captures settings page. The section renders three stacked inputs (endpoint URL, model name, API key) that write to the existing PUT /settings/captures mutation on blur, so a user typing a URL doesn't spam optimistic updates on every keystroke. Model and API-key inputs stay disabled until the endpoint field has a value, and a small footnote reports whether the built-in Qwen3 or the remote endpoint is currently active.
Adds translation strings for the "Custom LLM endpoint (advanced)"
section: title, description, three input placeholders, and the
two status messages ("using built-in Qwen3" vs "sending every
refinement to <endpoint>"). Other locales fall back to English
until a native translation lands.
Fills in the missing docstrings CodeRabbit flagged on this PR: - OpenAICompatLLMBackend: __init__ / is_loaded / generate + the two private helpers (_build_messages, _extract_content). - services.settings: update_capture_settings (which now propagates the custom-LLM config) plus the pre-existing _get_or_create_capture_row, _get_or_create_generation_row, and update_generation_settings helpers that were missing coverage on the files this PR already touches. Brings the coverage on files modified in this PR from 59.4 % to 91.9 %, above the 80 % threshold.
- Make the custom LLM API key write-only: replace the plaintext response field with a boolean ``custom_llm_api_key_configured`` flag on ``CaptureSettingsResponse``, computed via a ``model_validator(mode= 'before')`` so the raw value is dropped before Pydantic materialises the response. The settings UI reads the flag, keeps the input blank on load, wipes the field after a successful save, and adds an explicit "Clear" action — the key never survives on the client where a browser cache or dev-tools inspection could grab it. - Disclose that both refinement and personality rewrites now travel through the configured endpoint: update the customEndpoint status string and swap the "fully local, no cloud" sidebar bullet for a "runs remotely" variant that names the endpoint when it's active. en and ja both updated. - Add explicit accessible labels for the three custom-endpoint fields (URL / model / API key) so screen readers can distinguish them; the previous ``SettingRow`` title had no ``htmlFor`` and the inputs had no ``aria-label``. - Guard against structured (non-string) ``choices[0].message.content`` in ``_extract_content``: tool-use / vision servers sometimes return content parts arrays and used to trip ``AttributeError`` inside ``.strip()``; raise a clear ``ValueError`` instead. - Strengthen the few-shot integration test: pass an arbitrary ``ping → PONG``, ``foo → BAR`` mapping and assert the mapped-shape token leads the response so a passing run actually proves the ``examples`` field wasn't silently dropped in transit.
CodeRabbit flagged a race between ``set_llm_config`` and ``get_llm_backend``: the writer updated the endpoint/model/key globals before acquiring the lock, while the reader's fast path returned a cached backend without any lock. A request that raced a settings update could therefore reach a cached ``OpenAICompatLLMBackend`` still pointing at the previous URL while the freshly-typed key had already been swapped in — sending a fresh credential to a stale endpoint (or the reverse) is exactly the shape of leak we've been trying to avoid. Fold the config snapshot, the change detection, the cache invalidation, the cache lookup, and the on-miss constructor call all under ``_llm_backends_lock``. The Qwen fallback still runs outside the lock — its own dispatch can take multiple seconds to load a model and we don't want that blocking concurrent ``set_llm_config`` writes. ``_get_openai_compat_backend`` disappears (it was a private helper with no external callers) since the resolution now lives inline in ``get_llm_backend`` where the config read happens.
Two CodeRabbit follow-ups on the ``__init__.py`` lock work: - Extract ``"openai_compat"`` into a module-level ``_OPENAI_COMPAT_CACHE_KEY`` constant so ``set_llm_config`` (cache pop), ``get_llm_backend`` (cache lookup), and the on-miss install can't drift on the string literal. - Rewrite the comment that used to describe the Qwen fallback as having "its own lock". ``get_llm_backend_for_engine`` actually reuses the same non-reentrant ``_llm_backends_lock``, and the release-before-call ordering is load-bearing — a future edit that nested the fallback inside the ``with`` block above would self-deadlock the calling thread. Make that constraint explicit so the pattern is defensible on read.
The commit hook computed `trimmed` for the empty-check but then sent the untrimmed draft, so a bearer token with surrounding whitespace (paste from Notion / a code block) went to the remote as-is and got rejected with 401 — surfacing as a confusing 'auth failed' toast when the raw pasted key was fine. Addresses the AI Code Review Agent finding on #948 (Logic & Correctness, Medium): commitCustomLlmApiKey sends customLlmApiKeyDraft instead of the pre-trimmed variable.
…ndpoint failures clearly - unload/check/load plumbing for the qwen_llm engine addresses the local backend explicitly so the Models page still manages the on-device model while a custom endpoint is active (load_model was a no-op on the remote backend, so Download finished instantly without downloading) - /capture/readiness reports the LLM gate green and names the remote model when an endpoint is configured, so the hotkey is not blocked on a Qwen download the app will never use - the remote backend wraps HTTP, transport and non-JSON failures in a RuntimeError that names the endpoint and status; /llm/generate returns it as 502 instead of the generic 500 - fake OpenAI-compatible server tests: request shape, bearer auth, legacy response shape, failure modes, dispatch switching, key masking, settings sync, readiness, and a route-level round trip - CHANGELOG [Unreleased] entry Co-authored-by: capy-ai-staging[bot] <305915985+capy-ai-staging[bot]@users.noreply.github.com>
…emote model label - invalidate capture-readiness when custom_llm_endpoint / custom_llm_model change, so clearing the endpoint re-checks the local Qwen cache - follow redirects on the remote client (same as services/cuda.py) - endpoint fields no longer gated on auto-refine: personality compose and rewrite use the endpoint regardless, so the control must stay reachable - refinement and personality record the remote model name instead of the requested Qwen size when the remote backend did the work - tests for the redirect and the label Co-authored-by: capy-ai-staging[bot] <305915985+capy-ai-staging[bot]@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Prepared from #947 by @ext-sakamoro. Their commits are kept with original authorship; this branch rebases them on current main and adds the fixes listed below so it can merge cleanly.
What it does
Settings → Captures → Refinement gains a Custom LLM endpoint (advanced) section: endpoint URL, model name, and an optional API key. When both URL and model are set, dictation refinement, personality compose/rewrite and
POST /llm/generatego to{endpoint}/chat/completionson any OpenAI-compatible server (llama.cpp, vLLM, LM Studio, LocalAI, Ollama's shim, OpenRouter, OpenAI). Blank keeps the bundled local Qwen3 exactly as before. The key is stored incapture_settingslike the other settings (same as the cloud key incloud_settings) but is write-only over the API: responses carry onlycustom_llm_api_key_configured. Config is seeded on startup and re-synced on every settings write, so no restart is needed.Independent implementation from Voicebox's own
LLMBackendprotocol and the public OpenAI chat-completions spec.Changes beyond the original PR
backend/database/models.py: kept main'sdatetime.now(UTC)forupdated_atalongside the three new columns.unload_model_by_config,check_model_loaded,get_model_load_func) addressedget_llm_model(), which returns the remote backend once an endpoint is active;load_modelis a no-op there, so "Download Qwen3" finished instantly without downloading. They now address the localqwen_llmengine explicitly./capture/readinessreports the LLM gate green and names the remote model when an endpoint is configured; before, the dictation hotkey stayed blocked on a Qwen download the app would never use.RuntimeErrornaming the endpoint and status (no local paths);/llm/generatereturns that as 502 instead of the generic "LLM generation failed" 500. The refine route already forwardsstr(e), so the dictation pill shows the same message.backend/tests/test_openai_compat_backend.py: a fake in-process OpenAI-compatible server checks the request shape (messages, bearer,stream: false, few-shot examples), legacychoices[0].text, 401/unreachable/non-JSON/empty-choices failure modes, dispatch switching and cache invalidation, key masking, settings-write → dispatch sync, startup bootstrap, readiness, and a route-level round trip throughPUT /settings/captures,GET /capture/readiness,POST /llm/generate.[Unreleased]entry.Verification
CapturesPage.tsxandtypes.tstest_progress.py::test_hf_progress_tracker; the extra skips are the contributor's env-gated live integration tests.Closes #947