Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(brain): a generic OpenAI-compatible provider for self-hosted models
Ruben Lütke71b996c454f7
diff --git a/jarvis/plugins/brain/local_openai.py b/jarvis/plugins/brain/local_openai.pynew file mode 100644index 0000000000..ea2b76a83c--- /dev/null+++ b/jarvis/plugins/brain/local_openai.py@@ -0,0 +1,139 @@+"""Generic local OpenAI-compatible brain (HuggingFace transformers serve & co).++One card for every self-hosted server that speaks the OpenAI Chat-Completions+format: HuggingFace ``transformers serve`` (port 8000), llama.cpp+``llama-server`` (port 8080), vLLM, LM Studio (port 1234) — and TGI installs+keep working, though TGI itself is in maintenance mode and never the+recommendation. Ollama has its own dedicated provider; this is the+bring-your-own-server slot.++Unlike the cloud brains there is NO vendor default endpoint — a base URL is+REQUIRED and its absence raises an honest, example-bearing error instead of+guessing a port. The credential is OPTIONAL (``local_openai_api_key`` /+``LOCAL_OPENAI_API_KEY``): most local servers ignore it, some (LM Studio+behind a reverse proxy, vLLM with ``--api-key``) check it. Keyless by design+(§3 / AP-22): ``local-openai`` stays ABSENT from+``PROVIDER_SECRET_CANDIDATES`` so the key-aware resolver treats it as always+reachable and a dead server just fast-fails across families.++Vision is deliberately declared unsupported: whether a given local server+accepts image content is unknowable here, and the shared streamer then DROPS+images with a warning instead of letting a text-only server reject the whole+turn. Vision users take the Ollama card (which negotiates real multimodal+models) or a cloud brain.+"""++from __future__ import annotations++import logging+from collections.abc import AsyncIterator+from typing import Any++import httpx++from jarvis.core import config as cfg+from jarvis.core.protocols import BrainDelta, BrainRequest++from ._openai_base import stream_complete+from .ollama import normalize_server_root++log = logging.getLogger(__name__)++# Same shape as the Ollama timeout: a dead local server must fail fast so the+# fallback chain crosses families; a slow CPU-bound generation may stream long.+CLIENT_TIMEOUT = httpx.Timeout(connect=2.0, read=120.0, write=30.0, pool=30.0)++_NO_BASE_URL_HELP = (+ "The local OpenAI-compatible provider needs a server URL — set it on the "+ 'provider card (or [brain.providers."local-openai"].base_url). Examples: '+ "HuggingFace transformers serve: http://localhost:8000 - "+ "llama.cpp llama-server: http://localhost:8080 - "+ "LM Studio: http://localhost:1234 - vLLM: http://localhost:8000."+)+++class LocalOpenAIBrain:+ name: str = "local-openai"+ # Conservative floor — the real window depends on the served model; the+ # manager treats this as a budget hint, not a hard cap.+ context_window: int = 32_768+ supports_tools: bool = True+ supports_vision: bool = False++ def __init__(self, model: str | None = None) -> None:+ self._model = (model or "").strip()+ self._client: Any = None+ self._server_root: str | None = None+ self._credential: str | None = None++ def can_call_tools(self) -> bool:+ return self.supports_tools++ def _resolve_root(self) -> str:+ if self._server_root is None:+ ep = cfg.resolve_provider_endpoint("local-openai", vendor_default_base_url=None)+ if not ep.base_url:+ raise RuntimeError(_NO_BASE_URL_HELP)+ # Root convention (same as the Ollama card): the stored value is+ # the SERVER root; ``/v1`` is appended here, and a pasted ``…/v1``+ # is normalized away instead of doubling up.+ self._server_root = normalize_server_root(ep.base_url)+ # Optional key: a team-proxy token wins, else the user's optional+ # local key, else a placeholder the server ignores.+ self._credential = ep.credential or cfg.get_secret(+ "local_openai_api_key", "LOCAL_OPENAI_API_KEY"+ )+ return self._server_root++ def _ensure_client(self) -> Any:+ if self._client is None:+ root = self._resolve_root()+ from openai import AsyncOpenAI++ self._client = AsyncOpenAI(+ api_key=self._credential or "local",+ base_url=f"{root}/v1",+ timeout=CLIENT_TIMEOUT,+ )+ return self._client++ async def _resolve_model(self) -> str:+ """The configured model, else the first one the server lists (``/v1/models``)."""+ if self._model:+ return self._model+ root = self._resolve_root()+ headers = {}+ if self._credential:+ headers["Authorization"] = f"Bearer {self._credential}"+ try:+ async with httpx.AsyncClient(timeout=CLIENT_TIMEOUT) as client:+ resp = await client.get(f"{root}/v1/models", headers=headers)+ resp.raise_for_status()+ data = resp.json().get("data") or []+ except Exception as exc:+ raise RuntimeError(+ f"Local OpenAI-compatible server not reachable at {root} — is it "+ "running? (transformers serve / llama-server / LM Studio / vLLM)"+ ) from exc+ names = [str(m.get("id") or "").strip() for m in data]+ names = [n for n in names if n]+ if not names:+ raise RuntimeError(+ f"The server at {root} lists no models (/v1/models is empty) — "+ "load a model in the server, or set one explicitly on the card."+ )+ self._model = names[0]+ log.info("local-openai: no model configured — using first served: %s", self._model)+ return self._model++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ client = self._ensure_client()+ model = await self._resolve_model()+ async for delta in stream_complete(+ client, model, req, supports_vision=self.supports_vision+ ):+ yield delta++ def estimate_cost(self, req: BrainRequest) -> float:+ # Local inference has no per-token bill.+ return 0.0diff --git a/tests/unit/plugins/brain/test_local_openai.py b/tests/unit/plugins/brain/test_local_openai.pynew file mode 100644index 0000000000..f4723479fc--- /dev/null+++ b/tests/unit/plugins/brain/test_local_openai.py@@ -0,0 +1,195 @@+"""Generic local OpenAI-compatible brain: required base URL, optional key.++The card covers HuggingFace transformers serve, llama.cpp llama-server,+LM Studio, and vLLM with ONE adapter. Unlike the cloud brains there is no+vendor default endpoint — a missing base URL must raise an honest,+example-bearing English error, never guess a port. The key is optional and+only forwarded when the user stored one.+"""++from __future__ import annotations++from typing import Any++import httpx+import pytest++import jarvis.core.config as cfg+from jarvis.core.config import BrainConfig, BrainProviderConfig, JarvisConfig+from jarvis.plugins.brain.local_openai import LocalOpenAIBrain+++class _FakeOpenAI:+ last_kwargs: dict[str, Any] = {}++ def __init__(self, **kwargs: Any) -> None:+ _FakeOpenAI.last_kwargs = kwargs+++def _with_base_url(url: str | None, monkeypatch, stored_key: str | None = None) -> None:+ providers = {}+ if url is not None:+ providers["local-openai"] = BrainProviderConfig(base_url=url)+ conf = JarvisConfig(brain=BrainConfig(providers=providers))+ monkeypatch.setattr(cfg, "load_config", lambda: conf)+ monkeypatch.setattr(+ cfg,+ "get_secret",+ lambda key, env=None: stored_key if key == "local_openai_api_key" else None,+ )+++# ── Base URL is REQUIRED ─────────────────────────────────────────────────+def test_missing_base_url_gives_honest_examples(monkeypatch) -> None:+ _with_base_url(None, monkeypatch)+ with pytest.raises(RuntimeError) as err:+ LocalOpenAIBrain()._resolve_root()+ msg = str(err.value)+ # The error must teach the fix: the config key and real example ports.+ assert "local-openai" in msg+ assert "http://localhost:8000" in msg # transformers serve / vLLM+ assert "http://localhost:8080" in msg # llama.cpp llama-server+ assert "http://localhost:1234" in msg # LM Studio+++def test_client_appends_v1_to_root(monkeypatch) -> None:+ import openai++ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)+ _with_base_url("http://localhost:8000", monkeypatch)+ LocalOpenAIBrain()._ensure_client()+ assert _FakeOpenAI.last_kwargs["base_url"] == "http://localhost:8000/v1"+ # No stored key → placeholder the server ignores.+ assert _FakeOpenAI.last_kwargs["api_key"] == "local"+++def test_client_normalizes_pasted_v1(monkeypatch) -> None:+ import openai++ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)+ _with_base_url("http://localhost:1234/v1/", monkeypatch)+ LocalOpenAIBrain()._ensure_client()+ assert _FakeOpenAI.last_kwargs["base_url"] == "http://localhost:1234/v1"+++def test_optional_key_is_forwarded_when_stored(monkeypatch) -> None:+ import openai++ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)+ _with_base_url("http://localhost:8000", monkeypatch, stored_key="sk-local-test")+ LocalOpenAIBrain()._ensure_client()+ assert _FakeOpenAI.last_kwargs["api_key"] == "sk-local-test"+++def test_client_timeout_fast_connect_wide_read(monkeypatch) -> None:+ import openai++ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)+ _with_base_url("http://localhost:8000", monkeypatch)+ LocalOpenAIBrain()._ensure_client()+ timeout = _FakeOpenAI.last_kwargs["timeout"]+ assert timeout.connect <= 2.0+ assert timeout.read >= 120.0+++# ── Model discovery via /v1/models ───────────────────────────────────────+class _FakeResponse:+ def __init__(self, payload: dict[str, Any]) -> None:+ self._payload = payload++ def raise_for_status(self) -> None:+ return None++ def json(self) -> dict[str, Any]:+ return self._payload+++class _FakeAsyncClient:+ payload: dict[str, Any] = {}+ fail: bool = False+ last_url: str | None = None+ last_headers: dict[str, str] | None = None++ def __init__(self, **kwargs: Any) -> None:+ pass++ async def __aenter__(self) -> _FakeAsyncClient:+ return self++ async def __aexit__(self, *exc: Any) -> None:+ return None++ async def get(self, url: str, headers: dict[str, str] | None = None) -> _FakeResponse:+ _FakeAsyncClient.last_url = url+ _FakeAsyncClient.last_headers = headers+ if _FakeAsyncClient.fail:+ raise httpx.ConnectError("connection refused")+ return _FakeResponse(_FakeAsyncClient.payload)+++def fake_models(monkeypatch):+ monkeypatch.setattr(httpx, "AsyncClient", _FakeAsyncClient)+ _FakeAsyncClient.fail = False+ _FakeAsyncClient.payload = {}+ _FakeAsyncClient.last_url = None+ _FakeAsyncClient.last_headers = None+ return _FakeAsyncClient+++async def test_discovery_uses_first_served_model(monkeypatch, fake_models) -> None:+ _with_base_url("http://localhost:8000", monkeypatch)+ fake_models.payload = {"data": [{"id": "Qwen/Qwen3.5-9B"}, {"id": "other"}]}+ brain = LocalOpenAIBrain()+ assert await brain._resolve_model() == "Qwen/Qwen3.5-9B"+ assert fake_models.last_url == "http://localhost:8000/v1/models"+++async def test_discovery_sends_bearer_when_key_stored(monkeypatch, fake_models) -> None:+ _with_base_url("http://localhost:8000", monkeypatch, stored_key="sk-local-test")+ fake_models.payload = {"data": [{"id": "m"}]}+ await LocalOpenAIBrain()._resolve_model()+ assert fake_models.last_headers == {"Authorization": "Bearer sk-local-test"}+++async def test_empty_model_list_gives_honest_error(monkeypatch, fake_models) -> None:+ _with_base_url("http://localhost:8000", monkeypatch)+ fake_models.payload = {"data": []}+ with pytest.raises(RuntimeError) as err:+ await LocalOpenAIBrain()._resolve_model()+ assert "/v1/models is empty" in str(err.value)+++async def test_unreachable_server_gives_honest_error(monkeypatch, fake_models) -> None:+ _with_base_url("http://localhost:8000", monkeypatch)+ fake_models.fail = True+ with pytest.raises(RuntimeError) as err:+ await LocalOpenAIBrain()._resolve_model()+ msg = str(err.value)+ assert "not reachable" in msg+ assert "http://localhost:8000" in msg+++# ── Protocol surface ─────────────────────────────────────────────────────+def test_capability_flags_and_cost() -> None:+ brain = LocalOpenAIBrain(model="x")+ assert brain.supports_tools is True+ assert brain.can_call_tools() is True+ # Deliberately False: whether an arbitrary local server accepts image+ # content is unknowable — the shared streamer then DROPS images with a+ # warning instead of letting a text-only server reject the whole turn.+ assert brain.supports_vision is False+ req_like = type("R", (), {"messages": (), "max_tokens": 100})()+ assert brain.estimate_cost(req_like) == 0.0+++def test_wizard_whitelists_the_optional_secret() -> None:+ """Saving the optional key from the app requires the wizard slot to exist+ (ALLOWED_SECRET_KEYS is derived from it)."""+ from jarvis.setup.wizard import SECRETS++ spec = next(s for s in SECRETS if s.key == "local_openai_api_key")+ assert spec.env_fallback == "LOCAL_OPENAI_API_KEY"+ # App-only: local servers usually need no key — it must not lengthen+ # first-run onboarding.+ assert spec.prompt is False