Skip to content

Multi-Provider LLM Support

Vector Companion supports three LLM providers via the ModelBackend Protocol: Ollama (the default), a llama.cpp router-mode HTTP server (LlamaServerBackend, OpenAI-compatible), and the NInfer engine (NinferBackend, OpenAI-compatible chat/vision with a supervisor-managed native inference engine).

Provider Selection

The active provider is controlled by config.llm_provider:

Value Backend Description
"ollama" OllamaModelBackend Ollama Python client, connects to 127.0.0.1:11434 (default)
"llama_server" LlamaServerBackend llama.cpp router-mode llama-server daemon (OpenAI-compatible HTTP), multi-model resident with dynamic load/unload. User-started, app never spawns/kills it
"ninfer" NinferBackend NInfer engine (OpenAI-compatible chat + vision) at 127.0.0.1:8010; engine args managed through the NInfer supervisor at 127.0.0.1:8099. Embeddings/rerank stay on the llama.cpp router

Switch providers at runtime via the Parameters panel in the Tauri desktop UI (Provider dropdown), or by editing config/config.py.

Provider persistence: When you switch providers via the UI, the selection persists to SQLite (app.provider key). On startup, the backend loads the persisted provider before creating the ModelBackend, so your choice survives restarts. Per-provider model selections are also saved (app.models.ollama / app.models.llama_server / app.models.ninfer) -- switching providers automatically restores that provider's saved model roles. A legacy persisted llama_cpp provider is transparently migrated to llama_server at startup (its orphaned app.models.llama_cpp key is deleted).

Cloud mode guard: Switching to llama_server or ninfer automatically disables cloud_mode because Ollama-specific cloud endpoints (e.g., qwen3-vl:235b-cloud) are not available via those providers. A CONFIG_UPDATED event fires so the UI reflects the change immediately.

ModelBackend Protocol

The ModelBackend Protocol (core/model/model_backend.py) defines 8 methods that any provider backend must implement:

Method Purpose
chat_stream() Async streaming via async generator, yield raw tokens
chat_stream_structured() Yield ChatStreamChunk(content, thinking, tool_calls, done, extra) objects
chat_stream_structured_sync() Sync version for run_in_executor compatibility (agent_classes.py pattern)
chat() Non-streaming dict response, normalized across providers
embed() Generate embeddings, return list[list[float]]
list_models() List available models on the provider
health_check() Verify provider is reachable and healthy
cancel() Signal in-flight cancellation (best-effort; llama.cpp does not support mid-stream interrupt)

All methods return normalized structures identical across providers. _normalize_chunk() converts ChatStreamChunk to Ollama-style dicts for consumer compatibility.

Factory Pattern

from core.model.model_backend import create_model_backend

# Reads config.llm_provider automatically
backend = create_model_backend(backend=config.llm_provider, default_model=config.language_model)

# Register custom backends
from core.model.model_backend import register_backend
register_backend("my_custom", MyCustomBackend)

llama.cpp Router-Mode Server (llama_server)

LlamaServerBackend (core/model/llama_server_backend.py) talks OpenAI-compatible JSON to a user-started llama-server --models-preset ... daemon (default http://127.0.0.1:8080). The app never spawns or kills the router — the same contract as Ollama. If the daemon is down, health_check() returns an actionable status ("start it via the router launch script") instead of crashing.

Setup

  1. Start the router as a daemon (e.g. llama-server --models-preset D:\ai\llamacpp\router\preset.ini --host 127.0.0.1 --port 8080). Models are HF-cache-style ids (e.g. Qwen/...-GGUF:Q8_0) — no alias map, the app uses the exact ids the router reports from GET /models.
  2. Configure:
# config/config.py
llm_provider = "llama_server"
llama_server_base_url = "http://127.0.0.1:8080"     # router host/port
llama_server_preset_path = r"D:\ai\llamacpp\router\preset.ini"  # for num_ctx hot-apply
llama_server_model_dir = r"D:\ai\llamacpp\models"  # informational; models come from the router

Sampling

/v1/chat/completions accepts all 24 sampling keys per request (llama.cpp extends the OpenAI body), so every UI slider — DRY, XTC, sigma, dynatemp, adaptive-p, penalties, repeat_last_n, typical_p — reaches the server, plus the router-section samplers (chain override, e.g. ma = min-p + adaptive-p) and logit_bias (JSON object, e.g. {"27455": -100}) text inputs. num_predict is mapped to max_tokens. samplers and logit_bias are forwarded only when set — an empty samplers would wipe the server's default chain, and an empty bias object is a no-op.

Tool-call continuation clamp. Once a tool call has fired in the current turn, the agent loop sets the app-level tool_round kwarg (same gate as the DRY/XTC zeroing) and LlamaServerBackend pins that request's sampling to a Gemma-safe profile (temperature 1.0, top-p 0.95, top-k 64, all penalties/DRY/XTC/adaptive neutralized; max_tokens, seed and logit_bias preserved) — the loose Gemma 4 tool grammar (llama.cpp PR #31915) constrains JSON shape but not values, so aggressive style sampling corrupts tool-call arguments into server 500s. The first (decision) round of every turn and all tool-less requests always use your raw UI profile.

A built-in default ships for Gemma 4: config.gemma_stop_word_bias (gemma_stop_word_bias_enabled on by default) hard-bans (-100) the four whole-word stop/Stop tokens in the Gemma 4 vocab (4721, 11412, 17348, 24688) to curb the model's habit of spamming the standalone word mid-roleplay. build_generation_options() merges it into logit_bias only when the active generation model is a Gemma 4 model, so the vocab-specific ids never penalize unrelated tokens on other families; a key you set in the logit_bias box wins on collision. Set gemma_stop_word_bias_enabled = False in config/config.py to opt out.

num_ctx (load-time)

num_ctx is not a request parameter — it is fixed per model at load time in the router preset INI (ctx-size). The [*] section is the default that every model inherits — including cache models that are not listed in the INI — while a per-model section can override it (per-model windows are legal; verified against a live router). A model already running keeps its context until it is unloaded (manually, by LRU, or by a preset change) and reloaded; the new value then applies at load time — the same deferred semantics as Ollama.

  1. backend.rewrite_preset_ctx(n) rewrites ctx-size in the preset's [*] section (default for all models)
  2. GET /models?reload=1 tells the router to re-read the preset; any loaded instance whose source changed is unloaded
  3. The next time the model loads, it comes up with the new context

set_num_ctx() wraps 1+2; applied=true means the new value is committed and takes effect on the model's next load — it does not disturb currently-running models.

Thinking and tools

  • Thinking arrives as a native reasoning_content field (no regex). think maps to chat_template_kwargs.enable_thinking (+ reasoning_effort for level strings).
  • Tool calls arrive in OpenAI shape. llama.cpp streams each tool call as fragments — the first delta carries id + name, later deltas carry only index + argument slices — so the backend merges deltas by index and yields the complete call once, on the final chunk (finish_reason set). That matches Ollama's one-complete-tool-call-per-chunk contract, which the agent's per-chunk tool execution depends on. The agent also parses raw JSON-text arguments into dicts (_normalize_tool_call), so both providers deliver the same flat shape. The backend normalises the app's Ollama-style tool schemas ({"function": {...}}) to the OpenAI shape ({"type": "function", "function": {...}}) automatically — the router 500s on a missing type ("Failed to parse tools: Missing tool type").
  • embed() uses the router's real /v1/embeddings endpoint; Ollama serves embeddings via its native API. Synchronous embedding callers use embed_sync(), which creates a fresh httpx.Client per call to avoid sharing the async client's connection pool across event loops.

Embeddings require a router-registered embedding model

The router only serves models registered in its preset/cache, so for memory_mode (vector memory) to work under llama_server the embedding model role must be a router model id, not the Ollama tag. If the configured id is missing from the router catalog the app automatically falls back to the config.embedding_model_llama_server default (Qwen/Qwen3-Embedding-0.6B-GGUF:Q8_0) and persists it per-provider — set the embedding_model role (ModelsPanel) to a different id only when you serve another embedding model. Register an embedding GGUF in the preset with pooling flags:

[Qwen/Qwen3-Embedding-0.6B-GGUF:Q8_0]
pooling   = last
embedding = true

Per-provider model roles persist in SQLite (app.models.llama_server), and startup restores them before backend creation, so the router id is used for embedding calls even on a direct boot into llama_server. At restore time, stale flat model.{role} keys never override an applied per-provider value — the per-provider selection wins.

Reranking requires a router-registered reranker model

The same rule applies to the memory_mode reranker. The router's POST /v1/rerank endpoint answers 501 "Start it with --reranking" unless the serving model was started with embedding=true + pooling=rank. Under llama_server, ServerReranker (core/data/server_reranker.py) scores via that endpoint using the reranker_model_llama_server role (default Voodisss/Qwen3-Reranker-0.6B-GGUF-llama_cpp:Q8_0); under ollama the in-process CrossEncoder is used instead (see Data Persistence).

The router needs a preset section carrying the keys the spawned child process requires:

[Voodisss/Qwen3-Reranker-0.6B-GGUF-llama_cpp:Q8_0]
reranking = true
hf-repo = Voodisss/Qwen3-Reranker-0.6B-GGUF-llama_cpp:Q8_0
batch-size = 4096
ubatch-size = 4096
  • reranking = true — a single key that sets both embedding and pooling=rank; without it /v1/rerank answers 501.
  • hf-repo = <id> — without it the child is spawned with --alias only, and a llama-server with neither --model nor --hf-repo decides it is the router and never loads, so the router reports loading forever.
  • batch-size = 4096 + ubatch-size = 4096 — a rerank query/document pair is scored as a single sequence that must fit in one physical batch (limit = the smaller of the two); the [*] defaults (1024/512) 500 with "input is too large to process" on real conversation chunks.

This is mostly automatic: on lazy-load, ServerReranker.ensure_ready() appends the section to llama_server_preset_path if it is missing and patches missing keys into existing sections (explicit user values are respected; the write is idempotent), then runs GET /models?reload=1 so the router re-reads the INI. If the router still doesn't know the id (no HF cache entry), ensure_ready() queues a download via POST /models and defers loading to the next lazy-load attempt — the first RAG turn in the meantime falls back to top-3 embedding results. A model the router already knows from the cache but has not started is explicitly loaded via POST /models/load.

Scoring is native: the request is Jina-shaped (query + documents, top_n), the response relevance_score is the model's raw "yes" logit, and the instruction ("Given a query...") is baked into the GGUF's rerank chat template, so the per-call task string is nominal under this provider.

Router model management (load / LRU / unload)

The router runs each model as its own llama-server child process and manages the fleet:

  • Autoload — a request for an unloaded model loads it on demand (--models-autoload, default on), so the app never pre-loads anything.
  • Concurrent cap — --models-max (default 4, 0 = unlimited) limits loaded models. When a request arrives and every slot is full, it queues (FIFO) instead of evicting; the least-recently-used loaded model is unloaded to make room — with one rule: a model actively serving a request is never evicted mid-request.
  • Explicit control — POST /models/load / POST /models/unload with {"model": "<id>"}, plus DELETE /models?model=<id> to remove a cache-registered model entirely. GET /models?reload=1 re-reads the preset INI (see above).
  • Preset vs cache — source: "preset" means the id has a section in the INI (only place a per-model ctx window can live); source: "cache" means it was discovered from the HF model cache. Both inherit the [*] defaults — per-model ctx-size override is the only reason to add a section; the embedding model needs one (pooling flags, above).
  • Draft models — a speculative draft model (e.g. DFlash) is not a standalone loadable model; it is attached to its target via spec-* args, so it never owns a slot.

The app uses only autoload + ?reload=1 today; explicit load/unload is available from the terminal for memory management.

NInfer Engine (ninfer)

The third provider routes chat and vision through the NInfer engine (NinferBackend, core/model/ninfer_backend.py) — a supervisor-managed native inference engine speaking an OpenAI-compatible API.

Config key Default Purpose
config.ninfer_base_url http://127.0.0.1:8010 Engine chat/vision endpoint
config.ninfer_supervisor_url http://127.0.0.1:8099 NInfer supervisor (engine-arg control plane)
config.ninfer_model_id (artifact model id) Fallback model field for chat requests (used only when the live id cannot be queried)

Split responsibilities. The engine serves chat + vision only. It has no /v1/embeddings and no /v1/rerank — under ninfer the embedding backend and the memory_mode reranker stay on the llama.cpp router (llama_server_base_url, LlamaServerBackend), so the router daemon must be running for vector memory. set_provider and startup both wire a dedicated router embedding backend for this reason; the reranker factory (create_reranker()) selects ServerReranker for llama_server and ninfer.

Single-model pinning. The engine serves exactly one model, so at startup, on provider switch, and on backend hot-swap the app pins every local chat/vision model role (language_model, analysis_model, vision_model1, vision_model2, control_vision_model) to the engine's live public model id — resolve_engine_model_id() queries the engine's GET /v1/models and uses its single entry, falling back to config.ninfer_model_id when the engine is down or unreachable — so swapping the loaded checkpoint (e.g. flash-next ↔ 27b orcarouter) requires no config edit. Ids restored from another provider (e.g. a router GGUF) would 404 on the engine for chat, web search and vision. The exception is the embedding_model role, which must be a llama.cpp router model id (e.g. Qwen/Qwen3-Embedding-0.6B-GGUF:Q8_0), not the Ollama tag: if the configured id is missing from the router catalog the app automatically falls back to config.embedding_model_llama_server, applies it to config and the agents, and persists it under app.models.ninfer so the UI and the next startup agree. Only when the fallback id itself is missing from the catalog does the app log a prominent startup/switch warning — and vector memory fails until the role is set in the ModelsPanel. Under ninfer the router catalog is also merged into the available-models list, with each model's purpose classified from its llama-server CLI args (--embeddings → embedding, --reranking → reranker, otherwise chat) so the role dropdowns only offer real candidates.

Sampling surface. NinferBackend is a LlamaServerBackend subclass with a narrowed request body: it forwards only the keys the engine accepts — temperature, top_p, top_k (clamped 0..20), min_p, presence/frequency penalties, seed, max_tokens (from num_predict), and message_slice_len-derived messages slicing — and drops the llama.cpp-only advanced samplers (dry_multiplier, xtc_probability, logit_bias, typical_p, dynatemp_range, repeat_last_n, adaptive-p, etc.). Non-empty per-message name fields (OpenAI participant identity) are also stripped from the messages array — the engine's chat template cannot represent them and rejects such requests with 400 message_name_not_supported. The wire-gate (set_param validation against backend_caps.py) rejects the unsupported keys client-side, so the UI never submits a value the engine would drop. num_ctx is a dead knob under ninfer: the engine's context is fixed at startup by --max-context, so the key is absent from both the supported and load-time sets (hidden in the Parameters panel; set_num_ctx reports applied: False).

Thinking mapping. think_mode maps onto the engine's reasoning controls: off → enable_thinking: false; on → enable_thinking: true (no effort); medium → reasoning_effort: "medium"; high → reasoning_effort: "xhigh"; None → key omitted.

Supervisor proxy + engine-arg editor. NinferBackend proxies the supervisor's control plane (loopback + X-NInfer-Supervisor: 1 header) through main.py commands:

Command Supervisor call Notes
get_ninfer_state GET /api/state Compact engine/DXGI/NVLink/health snapshot
get_ninfer_config GET /api/config Live params + per-key schema (kind/group/label/help/range/choices)
set_ninfer_config POST /api/config Body {params, dry_run}; dry-run validates without touching the engine; applies only --max-concurrency and friendlier keys live, restart-requiring keys need a restart
ninfer_restart POST /api/restart Fire-and-forget engine restart (model reload ~15–60 s); UI polls get_ninfer_state until healthy

The Parameters panel renders a schema-driven engine-arg editor for the ninfer provider: it fetches get_ninfer_config, builds form controls from the schema (number/bool/choice inputs with min/max/clamping from the schema, grouped by the schema's group), dry-runs the change (set_ninfer_config with dry_run: true), applies, and prompts a restart when the supervisor reports engine_restart_required. The same set_param setting-key flow (VALID_SET_PARAM_SETTING_KEYS) persists ninfer_base_url / ninfer_supervisor_url / llama_server_base_url to SQLite (setting.{key} keys) and restores them at startup.

These commands fail with "Active provider is not ninfer (no supervisor proxy)" when a different backend is active.

Advanced Sampling Parameters

Ollama and llama_server expose the full 24-key llama.cpp sampler set — Ollama forwards all params via its options payload, and LlamaServerBackend maps each key into the router's OpenAI-compatible request body. The Parameters panel in the Tauri UI shows the full slider set for both providers (adaptive-p sliders under advanced; samplers/logit_bias text inputs in the llama.cpp router section). Under ninfer only the engine-supported subset shows (core samplers + penalties; see NInfer Engine) — visibility is driven by core/model/backend_caps.py via the provider_caps field in get_config.

Adaptive-P (llama.cpp b10448+): a terminal sampler that pins each selected token's probability to a target (default 0.4) and adapts it via an EMA of past selections (decay, default 0.9). adaptive_target = -1 disables it. It is not in the server's default chain — set samplers (e.g. ma = min-p + adaptive-p) to activate it; the value replaces the entire default chain.

Vision Format Adapter

Different providers use different image formats in multimodal messages:

Provider Format
Ollama "images": [bytes] key in message dict
llama.cpp server (router) OpenAI content blocks with image_url (adapter converts from Ollama form)
NInfer engine OpenAI content blocks with image_url (same adapter path as llama.cpp)

_normalize_vision_messages() in vision/image_processing.py handles the conversion automatically. When _vision_backend is None (Ollama), messages pass through unchanged.

LlamaServerBackend is additionally self-contained for the main agent chat path: the agent's auto-screenshot attaches Ollama-style images: [bytes] to the user message (agent_classes.py), and the backend converts those into OpenAI content blocks before serialising the request body. Without this, the raw bytes would break json.dumps() of the OpenAI body. (embed() is unaffected — text-only.)

Backend Injection

During startup (main.py), the created backend is injected into multiple subsystems:

  1. ModelManager -- create_model_manager(backend=_model_backend) -- ensures list_local_models() queries the configured provider, not always Ollama
  2. Agent factory -- build_agents(config, model_backend=backend, tool_host=tool_host)
  3. Embedding -- set_embedding_backend(backend) in core/data/embedding.py (falls back to Ollama if NotImplementedError). Under ninfer the injected embedding backend is a dedicated router LlamaServerBackend (the engine has no /v1/embeddings); all other providers inject the chat backend itself.
  4. Vision -- set_vision_backend(backend) in vision/image_processing.py

All subsystems use the provider-appropriate format automatically after injection. Backend creation happens early (after EventBus setup, before ModelManager) so all downstream components receive the correct backend.

Runtime Hot-Switch

Provider switching works at runtime without restarting main.py. When you change the provider in the Tauri UI or via the set_provider API command, the handler:

  1. Creates a new backend -- For ollama, creates the Ollama client (instant); for llama_server/ninfer, creates an httpx.AsyncClient pointed at the router/engine URL (instant). Under ninfer a second router embedding backend is also created and wired (see NInfer Engine).
  2. Cancels in-flight generation -- shared_state.generation_cancel_event.set() signals any running agent to stop streaming. The agent's token loop checks this event every iteration (agent_classes.py:989).
  3. Swaps all consumer references:
  4. _model_backend module global (main.py)
  5. agent.model_backend for each agent instance
  6. _embedding_backend via set_embedding_backend()
  7. _vision_backend via set_vision_backend()
  8. _model_manager.backend on the ModelManager instance
  9. Runs a non-blocking health check -- 3-second timeout via asyncio.wait_for. On success, logs "Hot-swap to {provider} (healthy: ...)". On failure (timeout, connection refused), logs a warning but proceeds -- the error will surface on the first agent call.
  10. Waits for generation to settle -- polls shared_state.agent_generating (max 10 seconds), then clears the cancel event.

The response message indicates the outcome: "switched to {provider}" on success, or "restart required" if the swap threw an exception (very rare -- e.g., factory returns unknown backend type).

Frontend: ModelsPanel Reactivity

The ModelsPanel in the Tauri desktop UI is provider-reactive:

  • Catalog refetch -- useEffect([provider]) dependency ensures the model catalog refetches when the provider changes
  • NInfer catalog merge -- under ninfer, get_available_models additionally merges the llama.cpp router catalog (embeddings/rerank models stay selectable even though the engine only serves chat/vision), tagged as router models
  • Cloud role filtering -- language_model_cloud and vision_model_cloud roles are hidden for non-ollama providers (Ollama-specific cloud endpoints)
  • Draft model is backend-only -- draft_model (speculative decoding for the llama_server provider) remains a valid backend role in get_models/set_model, but is not exposed as a ModelsPanel UI control
  • Loading state -- Displays "Loading models from {provider}..." while fetching, with AbortController cleanup on unmount/provider change
  • Model availability -- Models not in the catalog are marked (unavailable: name) with a disabled dropdown option
  • Purpose filtering -- Embedding models only appear for the embedding_model role; vision models for vision roles

Fallback Behavior

For backward compatibility during the transition period, all code paths fall back to direct Ollama calls when model_backend is None. This means:

  • Existing tests that don't inject a backend continue to work
  • config.llm_provider = "ollama" (default) produces zero behavioral change
  • The system degrades gracefully if the factory cannot create a backend