amoghrajesh commented on code in PR #76802: URL: https://github.com/apache/airflow/pull/76802#discussion_r4705510638
########## providers/common/ai/src/airflow/providers/common/ai/hooks/lmstudio.py: ########## @@ -0,0 +1,158 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +import time +from typing import Any + +import httpx2 + +from airflow.providers.common.ai.utils.readiness_errors import ( + extract_error_detail, + translate_readiness_errors, +) + +# Endpoints and fields: https://lmstudio.ai/docs/developer/rest/list and +# https://lmstudio.ai/docs/developer/rest/load +_LIST_MODELS_PATH = "/api/v1/models" +_LOAD_MODEL_PATH = "/api/v1/models/load" + + +def build_lmstudio_native_root(base_url: str) -> str: + """Return the server root of an LM Studio URL, dropping a trailing ``/api/v1`` or ``/v1``.""" + return base_url.rstrip("/").removesuffix("/api/v1").removesuffix("/v1") + + +class LMStudioBackend: + """ + Load control for a model served by LM Studio, through its native ``/api/v1/models`` endpoints. + + Pass the class to ``ensure_model_ready`` as ``backend_factory=LMStudioBackend``. + + The model list request gets *timeout* seconds and the load request gets what the list request left + of them. Each is an httpx2 timeout, which applies to the connect, write and read phases separately, + so the two requests together can still take longer than *timeout*. + + :param base_url: LM Studio URL; a trailing ``/v1`` (OpenAI-compatible) or ``/api/v1`` (native) + is dropped to reach the server root. + :param model_name: Model key as listed by ``GET /api/v1/models``; any other name raises + ``ValueError`` instead of loading a model. + :param transport: Optional httpx2 transport, mainly to stub the server in tests. + + :raises ValueError: If *base_url* is ``None`` or empty. + + Known limitation: no ``Authorization`` header is sent, so LM Studio with API token + authentication turned on is not supported. + """ + + def __init__( + self, + base_url: str | None, + model_name: str, + *, + transport: httpx2.BaseTransport | None = None, + ) -> None: + if not base_url: + raise ValueError("LMStudioBackend needs a base_url; pass the LM Studio server URL") + self.root = build_lmstudio_native_root(base_url) + self.model_name = model_name + self._transport = transport + + def load(self, *, timeout: float) -> None: + """ + Load the model unless LM Studio already lists it with a loaded instance, within *timeout* seconds. + + :raises TimeoutError: If a request exceeds the time it was given (see the class docstring). + :raises httpx2.ConnectError: If the server cannot be reached. + :raises httpx2.HTTPStatusError: If the server answers with an error status; the message says + whether listing or loading failed and carries the ``error`` text when the body has one, + otherwise the start of the response body. + :raises ValueError: If the model list is not a JSON object whose ``models`` is a list of objects + (the message carries the body's ``error`` text when there is one), or if none of its + entries has a ``key`` equal to the model name; nothing is loaded then. + """ + deadline = time.monotonic() + timeout + with httpx2.Client(transport=self._transport) as client: + with translate_readiness_errors( + server="LM Studio", + root=self.root, + timeout=timeout, + failure="could not list models", + timeout_failure="did not list its models", + ): + loaded = self._check_model_loaded(client, timeout=timeout) + if loaded: + return + if (remaining := deadline - time.monotonic()) <= 0: + raise TimeoutError( + f"LM Studio spent all {timeout} seconds listing models, leaving no time to load " + f"model '{self.model_name}'." + ) + with translate_readiness_errors( + server="LM Studio", + root=self.root, + timeout=remaining, + failure=f"could not load model '{self.model_name}'", + timeout_failure=f"did not finish loading model '{self.model_name}'", + ): + # LM Studio loads a second instance of an already-loaded model, hence the list first. + response = client.post( + f"{self.root}{_LOAD_MODEL_PATH}", json={"model": self.model_name}, timeout=remaining + ) + response.raise_for_status() + + def _check_model_loaded(self, client: httpx2.Client, *, timeout: float) -> bool: Review Comment: `_check_model_loaded` returns a `bool`, so it reads like a void check. Rename it to `_is_model_loaded` instaed? ########## providers/common/ai/tests/unit/common/ai/hooks/test_lmstudio.py: ########## @@ -0,0 +1,326 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +import json +import re +from unittest import mock + +import httpx2 +import pytest + +from airflow.providers.common.ai.hooks.lmstudio import LMStudioBackend, build_lmstudio_native_root + +_BASE_URL = "http://lmstudio:1234/v1" +_TIME = "airflow.providers.common.ai.hooks.lmstudio.time" + + +def _build_backend(handler, base_url: str = _BASE_URL, model_name: str = "qwen3") -> LMStudioBackend: + return LMStudioBackend(base_url, model_name, transport=httpx2.MockTransport(handler)) + + +def _build_models_response(*, loaded: bool, key: str = "qwen3") -> httpx2.Response: + instances = [{"id": key, "config": {"context_length": 4096}}] if loaded else [] + return httpx2.Response( + 200, + json={ + "models": [ + {"type": "llm", "key": "other-model", "loaded_instances": [{"id": "other-model"}]}, + {"type": "llm", "key": key, "loaded_instances": instances}, + ] + }, + ) + + +class TestBuildNativeRoot: + @pytest.mark.parametrize( + "base_url", + [ + "http://h:1234/v1", + "http://h:1234/v1/", + "http://h:1234/api/v1", + "http://h:1234/api/v1/", + "http://h:1234", + "http://h:1234/", + ], + ) + def test_returns_server_root(self, base_url): + assert build_lmstudio_native_root(base_url) == "http://h:1234" + + +class TestLMStudioBackendBaseUrl: + @pytest.mark.parametrize("base_url", [None, ""], ids=["base-url-none", "base-url-empty"]) + def test_missing_base_url_raises_value_error(self, base_url): + with pytest.raises(ValueError, match="needs a base_url"): + LMStudioBackend(base_url=base_url, model_name="qwen3") + + @pytest.mark.parametrize("base_url", ["http://h:1234/v1", "http://h:1234/api/v1"]) + def test_root_drops_api_suffix(self, base_url): Review Comment: Needed? `test_returns_server_root` already covers both suffixes, and `test_requests_go_to_the_native_root_for_either_base_url_form` covers them end to end. ########## providers/common/ai/src/airflow/providers/common/ai/hooks/lmstudio.py: ########## @@ -0,0 +1,158 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +import time +from typing import Any + +import httpx2 + +from airflow.providers.common.ai.utils.readiness_errors import ( + extract_error_detail, + translate_readiness_errors, +) + +# Endpoints and fields: https://lmstudio.ai/docs/developer/rest/list and +# https://lmstudio.ai/docs/developer/rest/load +_LIST_MODELS_PATH = "/api/v1/models" +_LOAD_MODEL_PATH = "/api/v1/models/load" + + +def build_lmstudio_native_root(base_url: str) -> str: Review Comment: `build_lmstudio_native_root` is public but only this module and its tests use it. It matches its sibling, `build_ollama_native_root`, so this is fine if that is the intent. Otherwise, rename it to `_build_lmstudio_native_root`. ########## providers/common/ai/tests/unit/common/ai/hooks/test_lmstudio.py: ########## @@ -0,0 +1,326 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +import json +import re +from unittest import mock + +import httpx2 +import pytest + +from airflow.providers.common.ai.hooks.lmstudio import LMStudioBackend, build_lmstudio_native_root + +_BASE_URL = "http://lmstudio:1234/v1" +_TIME = "airflow.providers.common.ai.hooks.lmstudio.time" + + +def _build_backend(handler, base_url: str = _BASE_URL, model_name: str = "qwen3") -> LMStudioBackend: + return LMStudioBackend(base_url, model_name, transport=httpx2.MockTransport(handler)) + + +def _build_models_response(*, loaded: bool, key: str = "qwen3") -> httpx2.Response: + instances = [{"id": key, "config": {"context_length": 4096}}] if loaded else [] + return httpx2.Response( + 200, + json={ + "models": [ + {"type": "llm", "key": "other-model", "loaded_instances": [{"id": "other-model"}]}, + {"type": "llm", "key": key, "loaded_instances": instances}, + ] + }, + ) + + +class TestBuildNativeRoot: + @pytest.mark.parametrize( + "base_url", + [ + "http://h:1234/v1", + "http://h:1234/v1/", + "http://h:1234/api/v1", + "http://h:1234/api/v1/", + "http://h:1234", + "http://h:1234/", + ], + ) + def test_returns_server_root(self, base_url): + assert build_lmstudio_native_root(base_url) == "http://h:1234" + + +class TestLMStudioBackendBaseUrl: + @pytest.mark.parametrize("base_url", [None, ""], ids=["base-url-none", "base-url-empty"]) + def test_missing_base_url_raises_value_error(self, base_url): + with pytest.raises(ValueError, match="needs a base_url"): + LMStudioBackend(base_url=base_url, model_name="qwen3") + + @pytest.mark.parametrize("base_url", ["http://h:1234/v1", "http://h:1234/api/v1"]) + def test_root_drops_api_suffix(self, base_url): + assert LMStudioBackend(base_url=base_url, model_name="qwen3").root == "http://h:1234" + + +class TestLMStudioBackendLoad: + def test_loaded_model_skips_the_load_request(self): + requests: list[httpx2.Request] = [] + + def handler(request: httpx2.Request) -> httpx2.Response: + requests.append(request) + return _build_models_response(loaded=True) + + _build_backend(handler).load(timeout=12.0) + + (request,) = requests + assert (request.method, request.url.path) == ("GET", "/api/v1/models") + assert request.extensions["timeout"]["read"] == 12.0 + + @mock.patch(_TIME, autospec=True) + def test_unloaded_model_is_listed_then_loaded_with_only_the_model_key(self, mock_time): + mock_time.monotonic.side_effect = [100.0, 104.0] + requests: list[httpx2.Request] = [] + + def handler(request: httpx2.Request) -> httpx2.Response: + requests.append(request) + if request.method == "GET": + return _build_models_response(loaded=False) + return httpx2.Response( + 200, + json={"type": "llm", "instance_id": "qwen3", "load_time_seconds": 3.2, "status": "loaded"}, + ) + + _build_backend(handler).load(timeout=12.0) + + get_request, post_request = requests + assert (get_request.method, get_request.url.path) == ("GET", "/api/v1/models") + assert (post_request.method, post_request.url.path) == ("POST", "/api/v1/models/load") + assert json.loads(post_request.content) == {"model": "qwen3"} + assert get_request.extensions["timeout"]["read"] == 12.0 + assert post_request.extensions["timeout"]["read"] == 8.0 + + @mock.patch(_TIME, autospec=True) + def test_load_request_is_not_sent_when_listing_used_the_whole_budget(self, mock_time): + mock_time.monotonic.side_effect = [100.0, 112.0] + methods: list[str] = [] + + def handler(request: httpx2.Request) -> httpx2.Response: + methods.append(request.method) + return _build_models_response(loaded=False) + + with pytest.raises(TimeoutError, match=r"all 12\.0 seconds listing models.*'qwen3'"): + _build_backend(handler).load(timeout=12.0) + + assert methods == ["GET"] + + @pytest.mark.parametrize( + "error", + [ + pytest.param("Unexpected endpoint or method. (GET /foo/api/v1/models)", id="error-string"), + pytest.param( + {"message": "Unexpected endpoint or method. (GET /foo/api/v1/models)"}, id="error-object" + ), + ], + ) + def test_models_missing_from_a_response_with_an_error_carries_the_error_text_without_loading(self, error): + methods: list[str] = [] + + def handler(request: httpx2.Request) -> httpx2.Response: + methods.append(request.method) + return httpx2.Response(200, json={"error": error}) + + with pytest.raises( + ValueError, + match=r"'models' of type NoneType, expected a list\. " + r"Its error: Unexpected endpoint or method\. \(GET /foo/api/v1/models\)", + ): + _build_backend(handler).load(timeout=5.0) + + assert methods == ["GET"] + + @pytest.mark.parametrize( + ("models", "listed"), + [ + pytest.param( + [{"key": "qwen/qwen3-0.6b", "loaded_instances": []}, {"key": "other"}], + "'qwen/qwen3-0.6b', 'other'", + id="other-keys", + ), + pytest.param([], "none", id="empty-list"), + pytest.param([{"type": "llm"}, {"key": "other"}], "'other'", id="entry-without-key-not-listed"), + ], + ) + def test_model_missing_from_the_list_raises_value_error_naming_listed_keys_without_loading( + self, models, listed + ): + methods: list[str] = [] + + def handler(request: httpx2.Request) -> httpx2.Response: + methods.append(request.method) + return httpx2.Response(200, json={"models": models}) + + expected = ( + "LM Studio at http://lmstudio:1234 lists no model with key 'qwen3'; " + f"listed keys: {listed}. Use one of the listed keys as the model name." + ) + with pytest.raises(ValueError, match=f"^{re.escape(expected)}$"): + _build_backend(handler).load(timeout=5.0) + + assert methods == ["GET"] + + def test_http_error_names_model_and_server_error_field(self): + def handler(request: httpx2.Request) -> httpx2.Response: + if request.method == "GET": + return _build_models_response(loaded=False) + return httpx2.Response( + 404, + json={ + "error": { + "type": "model_not_found", + "message": "Model qwen3 not found in downloaded models", + } + }, + ) + + with pytest.raises(httpx2.HTTPStatusError) as exc_info: + _build_backend(handler).load(timeout=5.0) + + assert str(exc_info.value) == ( + "LM Studio could not load model 'qwen3' (404): Model qwen3 not found in downloaded models" + ) + assert exc_info.value.response.status_code == 404 + assert isinstance(exc_info.value.__cause__, httpx2.HTTPStatusError) + + def test_list_error_says_listing_failed_not_loading(self): + backend = _build_backend(lambda request: httpx2.Response(401, json={"error": "unauthorized"})) + + with pytest.raises(httpx2.HTTPStatusError) as exc_info: + backend.load(timeout=5.0) + + message = str(exc_info.value) + assert "could not list models (401): unauthorized" in message + assert "load" not in message + + @pytest.mark.parametrize( + ("body", "expected"), + [ + pytest.param(httpx2.Response(200, text="<html>login</html>"), "not JSON", id="non-json-body"), + pytest.param(httpx2.Response(200, json=[{"key": "qwen3"}]), "JSON list", id="top-level-list"), + pytest.param(httpx2.Response(200, json={"models": None}), "NoneType", id="models-null"), + pytest.param(httpx2.Response(200, json={}), "NoneType", id="models-missing"), + pytest.param(httpx2.Response(200, json={"models": {"qwen3": {}}}), "dict", id="models-not-list"), + pytest.param( + httpx2.Response(200, json={"models": ["qwen3"]}), "not objects", id="entry-not-object" + ), + ], + ) + def test_unexpected_model_list_raises_value_error_without_loading(self, body, expected): + methods: list[str] = [] + + def handler(request: httpx2.Request) -> httpx2.Response: + methods.append(request.method) + return body + + with pytest.raises(ValueError, match=expected): + _build_backend(handler).load(timeout=5.0) + + assert methods == ["GET"] + + def test_matching_entry_without_loaded_instances_is_loaded(self): Review Comment: A missing key and null both reach `m.get("loaded_instances") is None`, so it is the same case as the null param of `test_loaded_instances_that_is_not_a_list_counts_as_not_loaded`. Fold it into that parametrize i think -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
