Skip to content

Add custom OpenAI-compatible LLM endpoint for refinement and personality - #1167

Merged
capy-ai-staging[bot] merged 11 commits into
mainfrom
prep/pr-947
Oct 7, 2026
Merged

capy-ai-staging[bot] merged 11 commits into
mainfrom
prep/pr-947

Conversation

@jamiepine

Copy link
Copy Markdown
Owner

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/generate go to {endpoint}/chat/completions on 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 in capture_settings like the other settings (same as the cloud key in cloud_settings) but is write-only over the API: responses carry only custom_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 LLMBackend protocol and the public OpenAI chat-completions spec.

Changes beyond the original PR

  • Rebase conflict in backend/database/models.py: kept main's datetime.now(UTC) for updated_at alongside the three new columns.
  • One follow-up commit:
    • The Models page plumbing (unload_model_by_config, check_model_loaded, get_model_load_func) addressed get_llm_model(), which returns the remote backend once an endpoint is active; load_model is a no-op there, so "Download Qwen3" finished instantly without downloading. They now address the local qwen_llm engine explicitly.
    • /capture/readiness reports 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.
    • The remote backend wraps HTTP, transport and non-JSON failures in a RuntimeError naming the endpoint and status (no local paths); /llm/generate returns that as 502 instead of the generic "LLM generation failed" 500. The refine route already forwards str(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), legacy choices[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 through PUT /settings/captures, GET /capture/readiness, POST /llm/generate.
    • CHANGELOG [Unreleased] entry.

Verification

  • typecheck + web build: pass; biome clean on CapturesPage.tsx and types.ts
  • backend pytest (Python 3.12, CPU torch): 250 passed / 1 failed / 13 skipped vs main baseline 238 / 1 / 8. The failure is the pre-existing test_progress.py::test_hf_progress_tracker; the extra skips are the contributor's env-gated live integration tests.
  • targeted: the new fake-server suite above (12 tests). Not run: a real llama.cpp/Ollama server and the MLX Qwen path.

Closes #947

Open in Capy

@capy-ai-staging capy-ai-staging Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Capy found 1 potential issue (1 medium).

View 4 other findings in Capy.

Open in Capy

@capy-ai-staging capy-ai-staging Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Capy found no issues.

View 1 other finding in Capy.

Open in Capy

Moroya Sakamoto and others added 11 commits October 7, 2026 00:38
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>
@capy-ai-staging
capy-ai-staging Bot merged commit 129d84f into main Oct 7, 2026
1 check passed
@capy-ai-staging
capy-ai-staging Bot deleted the prep/pr-947 branch October 7, 2026 00:39

@capy-ai-staging capy-ai-staging Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Capy found no issues.

Open in Capy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant