diff --git a/gknowledge/providers/openai_compatible.py b/gknowledge/providers/openai_compatible.py index aa67c4f..b1905d8 100644 --- a/gknowledge/providers/openai_compatible.py +++ b/gknowledge/providers/openai_compatible.py @@ -10,6 +10,7 @@ import json import urllib.error +import urllib.parse import urllib.request from .base import LLMMessage, LLMProvider, LLMResponse, ProviderError @@ -85,7 +86,6 @@ def complete( ) - DEFAULT_OLLAMA_BASE_URL = "http://localhost:11434/v1" DEFAULT_OLLAMA_MODELS_URL = f"{DEFAULT_OLLAMA_BASE_URL}/models" _OLLAMA_TIMEOUT = 2.0 @@ -148,6 +148,58 @@ def should_prefill_ollama_base_url(current_base_url: str | None) -> bool: return not cleaned or cleaned == "https://api.openai.com/v1" +def ollama_models_url(base_url: str) -> str: + """Turn an Ollama Base URL into its OpenAI-compatible models endpoint. + + Surrounding spaces and trailing slashes are dropped and ``/v1`` is added + when missing, so ``http://host:11434`` and ``http://host:11434/v1/`` both + give ``http://host:11434/v1/models``. + + Raises: + ValueError: the URL is not http(s) or has no host. + """ + cleaned = (base_url or "").strip().rstrip("/") + parts = urllib.parse.urlsplit(cleaned) + try: + parts.port # noqa: B018 - raises ValueError for an invalid port + except ValueError as exc: + raise ValueError("Base URL has an invalid port") from exc + if parts.scheme not in ("http", "https") or not parts.hostname: + raise ValueError("Base URL must start with http:// or https://") + if not cleaned.endswith("/v1"): + cleaned += "/v1" + return f"{cleaned}/models" + + +def ollama_detect_endpoint(base_url: str | None, *, explicit: bool) -> str: + """Pick the models endpoint for an Ollama detection. + + Only an explicit Detect click may use a Base URL the user typed. The + automatic probe, and a click while the Base URL is empty or still the + OpenAI default, go to the local default server. + + Raises: + ValueError: an explicit detection with a Base URL that is not http(s). + """ + if not explicit or should_prefill_ollama_base_url(base_url): + return DEFAULT_OLLAMA_MODELS_URL + return ollama_models_url(base_url or "") + + +def ollama_host_label(endpoint: str) -> str: + """Return ``host:port`` of an endpoint for status messages. + + Built from the host name and port only, so credentials or paths in the + URL never show up in the UI. + """ + parts = urllib.parse.urlsplit(endpoint) + host = parts.hostname or endpoint + if ":" in host: # IPv6 literal + host = f"[{host}]" + port = parts.port + return f"{host}:{port}" if port else host + + def resolve_ollama_model_selection( current_model: str, discovered_models: list[str], diff --git a/gknowledge/ui/preferences.py b/gknowledge/ui/preferences.py index 906cfbc..eabca6c 100644 --- a/gknowledge/ui/preferences.py +++ b/gknowledge/ui/preferences.py @@ -15,6 +15,8 @@ OllamaUnavailable, discover_ollama_models, get_ollama_selection_state, + ollama_detect_endpoint, + ollama_host_label, resolve_ollama_model_selection, should_prefill_ollama_base_url, ) @@ -130,7 +132,7 @@ def __init__(self, parent: Gtk.Window, project: Project, on_saved): # For Ollama the model list comes from local server discovery. self._ollama_model_list = Gtk.StringList.new([]) self._ollama_model_combo = Adw.ComboRow(title="Model", model=self._ollama_model_list, - subtitle="Discovered from local Ollama server") + subtitle="Discovered from Ollama server") self._ollama_model_combo.set_factory(_full_width_factory()) self._ollama_model_combo.set_list_factory(_full_width_factory()) self._ollama_model_combo.connect("notify::selected", self._on_ollama_model_changed) @@ -239,7 +241,7 @@ def _fill_models(self, models, err): # -- Ollama local discovery ---------------------------------------------- def _on_detect_clicked(self, *_a): - self._load_ollama_models() + self._load_ollama_models(explicit=True) def _on_ollama_model_changed(self, *_a): # "Custom…" reveals the free-text Model row; a discovered model hides it. @@ -267,7 +269,16 @@ def _get_current_ollama_model(self) -> str: return self._saved_ollama_model - def _load_ollama_models(self): + def _load_ollama_models(self, explicit: bool = False): + # Only an explicit Detect click may probe the Base URL the user typed; + # the automatic probe on provider change always stays on localhost. + try: + endpoint = ollama_detect_endpoint(self._base_url.get_text(), explicit=explicit) + except ValueError as exc: + self._ollama_row.set_subtitle(str(exc)) + return + host = ollama_host_label(endpoint) + self._ollama_request_id += 1 req_id = self._ollama_request_id self._ollama_probe_in_flight = True @@ -277,20 +288,19 @@ def _load_ollama_models(self): current_model = self._get_current_ollama_model() def work(): - # Always the local default: a URL left over from another provider - # must never receive an unrequested probe. try: - models = discover_ollama_models() + models = discover_ollama_models(endpoint) err = None except OllamaUnavailable: - models, err = [], "No Ollama server found at localhost:11434" + models, err = [], f"No Ollama server found at {host}" except Exception as exc: # noqa: BLE001 models, err = [], f"Could not list Ollama models: {str(exc)[:80]}" - GLib.idle_add(self._fill_ollama_models, req_id, current_model, models, err) + GLib.idle_add(self._fill_ollama_models, req_id, host, current_model, models, err) threading.Thread(target=work, daemon=True).start() - def _fill_ollama_models(self, req_id: int, current_model: str, models: list[str], err: str | None): + def _fill_ollama_models(self, req_id: int, host: str, current_model: str, + models: list[str], err: str | None): if req_id != self._ollama_request_id: return False @@ -322,7 +332,7 @@ def _fill_ollama_models(self, req_id: int, current_model: str, models: list[str] n = len(models) self._ollama_row.set_subtitle( - f"Ollama running at localhost ({n} model{'s' if n != 1 else ''} found)" + f"Ollama running at {host} ({n} model{'s' if n != 1 else ''} found)" ) self._ollama_models = list(models) diff --git a/tests/test_openai_compatible.py b/tests/test_openai_compatible.py index 847fb73..32197a2 100644 --- a/tests/test_openai_compatible.py +++ b/tests/test_openai_compatible.py @@ -20,6 +20,9 @@ OllamaUnavailable, discover_ollama_models, get_ollama_selection_state, + ollama_detect_endpoint, + ollama_host_label, + ollama_models_url, resolve_ollama_model_selection, should_prefill_ollama_base_url, ) @@ -177,3 +180,87 @@ def test_dropdown_index_maps_to_model_or_custom(): assert get_ollama_selection_state(2, models) == (None, True) # "Custom…" assert get_ollama_selection_state(-1, models) == (None, False) assert get_ollama_selection_state(0xFFFFFFFF, models) == (None, False) # GTK_INVALID_LIST_POSITION + + +# -- Detect at a custom Base URL (#57) ---------------------------------------- + +@pytest.mark.parametrize("base_url", [ + "http://192.168.1.50:11434", + "http://192.168.1.50:11434/", + "http://192.168.1.50:11434/v1", + "http://192.168.1.50:11434/v1/", + " http://192.168.1.50:11434/v1 ", +]) +def test_models_url_from_base_url(base_url): + assert ollama_models_url(base_url) == "http://192.168.1.50:11434/v1/models" + + +def test_models_url_keeps_https_and_paths(): + assert ollama_models_url("https://ollama.lan/proxy/v1") == "https://ollama.lan/proxy/v1/models" + + +@pytest.mark.parametrize("base_url", [ + "ftp://192.168.1.50:11434/v1", + "file:///etc/passwd", + "192.168.1.50:11434", + "http://", + "http://host:notaport/v1", +]) +def test_models_url_rejects_non_http_urls(base_url): + with pytest.raises(ValueError): + ollama_models_url(base_url) + + +def test_automatic_probe_always_stays_on_localhost(): + for base_url in ("", "https://api.openai.com/v1", "http://192.168.1.50:11434/v1", + "ftp://bad"): + assert ollama_detect_endpoint(base_url, explicit=False) == DEFAULT_OLLAMA_MODELS_URL + + +def test_explicit_detect_uses_a_typed_base_url(): + assert (ollama_detect_endpoint("http://192.168.1.50:11434/v1", explicit=True) + == "http://192.168.1.50:11434/v1/models") + + +@pytest.mark.parametrize("base_url", ["", " ", None, "https://api.openai.com/v1/"]) +def test_explicit_detect_without_a_typed_url_uses_localhost(base_url): + assert ollama_detect_endpoint(base_url, explicit=True) == DEFAULT_OLLAMA_MODELS_URL + + +def test_explicit_detect_rejects_a_non_http_base_url_without_a_request(): + with pytest.raises(ValueError): + ollama_detect_endpoint("ftp://192.168.1.50/v1", explicit=True) + + +def test_host_label_names_host_and_port_only(): + assert ollama_host_label(DEFAULT_OLLAMA_MODELS_URL) == "localhost:11434" + assert ollama_host_label("http://192.168.1.50:11434/v1/models") == "192.168.1.50:11434" + assert ollama_host_label("https://ollama.lan/v1/models") == "ollama.lan" + assert ollama_host_label("http://user:secret@10.0.0.2:11434/v1/models") == "10.0.0.2:11434" + assert ollama_host_label("http://[::1]:11434/v1/models") == "[::1]:11434" + + +@pytest.mark.parametrize("suffix", ["", "/", "/v1", "/v1/"]) +def test_explicit_detect_lists_models_from_a_custom_base_url(ollama, suffix): + server = ollama(json.dumps({"object": "list", "data": [{"id": "remote:7b"}]})) + base_url = server.url.removesuffix("/v1/models") + suffix + endpoint = ollama_detect_endpoint(base_url, explicit=True) + assert discover_ollama_models(endpoint) == ["remote:7b"] + assert server.requests == [("GET", "/v1/models", 0)] + + +def test_refused_connection_at_a_custom_base_url(): + port = _free_port() + endpoint = ollama_detect_endpoint(f"http://127.0.0.1:{port}", explicit=True) + assert ollama_host_label(endpoint) == f"127.0.0.1:{port}" + with pytest.raises(OllamaUnavailable): + discover_ollama_models(endpoint) + + +def test_slow_custom_base_url_times_out_as_unavailable(ollama): + server = ollama('{"data": []}', delay=1.0) + endpoint = ollama_detect_endpoint(server.url.removesuffix("/models"), explicit=True) + start = time.monotonic() + with pytest.raises(OllamaUnavailable): + discover_ollama_models(endpoint, timeout=0.2) + assert time.monotonic() - start < 1.0