kaxil commented on code in PR #76802:
URL: https://github.com/apache/airflow/pull/76802#discussion_r4710373303
##########
providers/common/ai/docs/self_hosted_models.rst:
##########
@@ -360,6 +363,60 @@ server. When it points at Ollama, pass ``OllamaBackend``
as the factory
hook = PydanticAIHook(llm_conn_id="pydanticai_default",
model_id="openai:llama3")
hook.ensure_model_ready(backend_factory=OllamaBackend)
+For LM Studio, pass ``LMStudioBackend``. It needs LM Studio 0.4.0 or later, the
+release that introduced the native
+`v1 REST API <https://lmstudio.ai/docs/developer/rest>`__ (see also the
+`API changelog <https://lmstudio.ai/docs/developer/api-changelog>`__). It lists
+the models with
+`GET /api/v1/models <https://lmstudio.ai/docs/developer/rest/list>`__ and sends
+`POST /api/v1/models/load <https://lmstudio.ai/docs/developer/rest/load>`__
+only when the model has no loaded instance.
+
+.. code-block:: python
+
+ from airflow.providers.common.ai.hooks.lmstudio import LMStudioBackend
+
+ hook = PydanticAIHook(llm_conn_id="pydanticai_default",
model_id="openai:qwen3")
+ hook.ensure_model_ready(backend_factory=LMStudioBackend)
+
+Things to know:
+
+- **List first, then load.** LM Studio answers a load request for a model that
+ is already loaded by loading a second instance of it, so the backend lists
the
+ models first and sends the load request only when the model has no loaded
+ instance. The load request returns once the model is loaded. A failed load is
+ reported with the server's error message when the response has one, or the
+ start of the response body otherwise.
+- **Model name and list shape.** The model name is compared with the ``key`` of
+ the listed models, so use the model key that LM Studio lists. If no listed
+ model has that key, ``ValueError`` names the listed keys and nothing is
+ loaded. A ``loaded_instances`` that is missing, empty or not a list counts as
+ not loaded, and an entry without a ``key`` never matches and is not listed.
If
+ the list is not a JSON object with a ``models`` list of objects, for example
+ when a proxy answers with a login page, ``ValueError`` is raised instead of
+ loading anyway.
+- **Timeout.** The list request gets ``timeout`` seconds and the load request
+ gets the time the list request left. Each is an httpx2 timeout, which applies
+ to the connect, write and read phases separately, so both requests together
+ can take longer than ``timeout``. A timeout message names the time that
+ request was given.
+- **Concurrent tasks.** The list and the load are two requests, not one atomic
+ step, so two tasks that start together can both see the model as not loaded
+ and both send a load request. Each of those loads is another instance, and as
+ the next item says, it stays in memory until you unload it.
+- **The model stays loaded.** The load request sends no TTL, and a model loaded
Review Comment:
This holds only for a load the backend sends. If an earlier LLM call
JIT-loaded the model, the list already shows an instance and nothing is sent,
so that instance keeps its TTL (60 idle minutes by default) and the next JIT
load of another model can still evict it. Could the bullet say that an instance
the backend finds already loaded keeps whatever TTL it was loaded with?
##########
providers/common/ai/src/airflow/providers/common/ai/hooks/pydantic_ai.py:
##########
@@ -681,15 +682,17 @@ def ensure_model_ready(
Opt-in, blocks the worker slot, and loads only this hook's own
connection. Details and
limits: :ref:`self_hosted_models_ensure_model_ready`.
- :param timeout: Seconds to wait for the load request, passed to the
backend as is.
+ :param timeout: Seconds to wait for the load request, passed to the
backend as is. A backend
+ may spend it over several requests.
:param backend_factory: Callable that takes the keyword arguments
``model_name`` (the
resolved name without its provider prefix) and ``base_url`` (the
connection host, or
``None``) and returns an object with ``load()`` (see
ModelReadinessBackend). When
given, the model prefix and connection host checks are skipped; a
missing model still
raises ``ValueError``. See
:ref:`self_hosted_models_readiness_backend`.
:raises ValueError: If *timeout* is not a positive finite number or no
model is configured;
also from the default ``OllamaBackend`` when neither the
connection host nor the
- ``OLLAMA_BASE_URL`` environment variable is set.
+ ``OLLAMA_BASE_URL`` environment variable is set, and from
``LMStudioBackend`` when the
+ connection has no host or the model list has an unexpected shape.
Review Comment:
`LMStudioBackend` also raises `ValueError` when no listed model's `key`
equals the model name, which is the one an LM Studio user is most likely to
hit. Worth naming here too, like the `load()` docstring does?
##########
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"),
Review Comment:
No test fails if the `if body.get("error")` check goes: these two cases
match `NoneType` with a search, so they still pass with ` Its error:
{"models":null}` appended. Could they anchor the match, e.g. `r"'models' of
type NoneType, expected a list\.$"`?
--
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]