kaxil commented on code in PR #76802:
URL: https://github.com/apache/airflow/pull/76802#discussion_r4689742406
##########
providers/common/ai/docs/self_hosted_models.rst:
##########
@@ -360,6 +360,48 @@ 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 first
+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's entry has no loaded instance. The check comes first
+because the LM Studio documentation, as of this writing, does not say what
+loading an already-loaded model does. The load documentation also does not say
+whether the request waits until the model is loaded or what an error response
+looks like, so the backend relies on neither: it treats a successful response
+as done and reports the ``error`` text of a failed response when there is one,
+or the start of the response body otherwise.
+
+The model name is compared with the ``key`` of the listed models, so use the
+model key that LM Studio lists. A ``loaded_instances`` that is missing, empty
or
+not a list counts as not loaded, and an entry without a ``key`` never matches.
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.
+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.
+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.
+``base_url`` may end in ``/v1`` or ``/api/v1`` and must be set (``ValueError``
+otherwise). The backend does not send an API token, so LM Studio with
+`authentication <https://lmstudio.ai/docs/developer/core/authentication>`__
+turned on is not supported. The load documentation does not mention an idle
Review Comment:
Does a model loaded through `/api/v1/models/load` ever unload on its own?
The load endpoint takes no `ttl`. The TTL page says `lms load` models have no
TTL by default and stay loaded until someone unloads them, and auto-evict
leaves them alone. If REST loads work the same way, each model a Dag preloads
stays in memory on the LM Studio host until someone unloads it. Can you try it
on a real server and write down what happens?
##########
providers/common/ai/docs/self_hosted_models.rst:
##########
@@ -360,6 +360,48 @@ 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 first
+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's entry has no loaded instance. The check comes first
+because the LM Studio documentation, as of this writing, does not say what
+loading an already-loaded model does. The load documentation also does not say
+whether the request waits until the model is loaded or what an error response
+looks like, so the backend relies on neither: it treats a successful response
+as done and reports the ``error`` text of a failed response when there is one,
+or the start of the response body otherwise.
+
+The model name is compared with the ``key`` of the listed models, so use the
+model key that LM Studio lists. A ``loaded_instances`` that is missing, empty
or
+not a list counts as not loaded, and an entry without a ``key`` never matches.
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.
+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.
+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.
+``base_url`` may end in ``/v1`` or ``/api/v1`` and must be set (``ValueError``
+otherwise). The backend does not send an API token, so LM Studio with
+`authentication <https://lmstudio.ai/docs/developer/core/authentication>`__
+turned on is not supported. The load documentation does not mention an idle
+TTL for models loaded this way; see LM Studio's
+`TTL and auto-evict
<https://lmstudio.ai/docs/developer/core/ttl-and-auto-evict>`__
+page for the settings it does describe:
Review Comment:
Ending this sentence on a colon makes the example below read as a TTL
example. The reader also gets about 30 lines of caveats before seeing how to
use it. Could the code block move up right after the first sentence, with the
caveats after it as a short list?
##########
providers/common/ai/src/airflow/providers/common/ai/utils/readiness_errors.py:
##########
@@ -0,0 +1,63 @@
+# 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
+
+from collections.abc import Iterator
+from contextlib import contextmanager
+
+import httpx2
+
+
+def extract_error_detail(response: httpx2.Response) -> str:
+ """Return the ``error`` field when it is a non-empty string, or the body
cut to a short length."""
+ try:
+ body = response.json()
+ except ValueError:
+ body = None
+ if isinstance(body, dict) and isinstance(error := body.get("error"), str)
and error:
+ return error
+ return response.text.strip()[:200] or response.reason_phrase
+
+
+@contextmanager
+def translate_readiness_errors(
+ *, server: str, root: str, timeout: float, failure: str, timeout_failure:
str
+) -> Iterator[None]:
+ """
+ Re-raise httpx2 errors from a readiness request with messages naming the
failed step.
+
+ :param server: Server name used to start each message, such as ``Ollama``.
+ :param root: Server root, named when the server cannot be reached.
+ :param timeout: Seconds reported in the timeout messages.
+ :param failure: Message after *server* for an error status, followed by
the status code and detail.
+ :param timeout_failure: Message after *server* for a read timeout,
followed by *timeout*.
+
+ :raises httpx2.HTTPStatusError: On an error status, with the server's
error text in the message.
+ :raises TimeoutError: On a connect timeout or any other timeout.
+ """
+ try:
+ yield
+ except httpx2.HTTPStatusError as e:
+ raise httpx2.HTTPStatusError(
+ f"{server} {failure} ({e.response.status_code}):
{extract_error_detail(e.response)}",
+ request=e.request,
+ response=e.response,
+ ) from e
+ except httpx2.ConnectTimeout as e:
Review Comment:
A stopped LM Studio or a mistyped host raises `httpx2.ConnectError`, which
isn't a `TimeoutException`, so it skips this block and comes out as a bare
`[Errno 111] Connection refused` with no server name, root or step. That's the
most common way to be unreachable, and `LMStudioBackend.load()`'s docstring
promises `TimeoutError` for it. Could this also catch `httpx2.ConnectError` and
re-raise it the way the `HTTPStatusError` branch does (same type, message
naming the server and root)? That keeps the hook's documented
`httpx2.TransportError` and fixes the same docstring line on
`OllamaBackend.load()`.
##########
providers/common/ai/src/airflow/providers/common/ai/hooks/pydantic_ai.py:
##########
@@ -630,15 +631,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
+ model list has an unexpected shape.
Review Comment:
`LMStudioBackend` also raises `ValueError` when the connection has no host,
since it has no env-var fallback like `OLLAMA_BASE_URL`. Worth naming that here
too?
##########
providers/common/ai/tests/unit/common/ai/hooks/test_pydantic_ai.py:
##########
@@ -1940,6 +1941,30 @@ def test_backend_factory_skips_the_host_check(self,
mock_ollama_cls):
stub.load.assert_called_once()
mock_ollama_cls.assert_not_called()
+ def test_backend_factory_can_return_an_lmstudio_backend(self):
+ requests: list[httpx2.Request] = []
+
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ if request.method == "GET":
+ return httpx2.Response(200, json={"models": [{"key": "qwen3",
"loaded_instances": []}]})
+ return httpx2.Response(200, json={"status": "loaded"})
+
+ hook, conn = self._build_hook(model_id="openai:qwen3",
host="http://lmstudio:1234/v1")
+
+ with patch.object(hook, "get_connection", return_value=conn):
+ hook.ensure_model_ready(
+ backend_factory=lambda model_name, base_url: LMStudioBackend(
Review Comment:
The lambda maps the arguments by hand, so this never runs the documented
`backend_factory=LMStudioBackend` form, which depends on
`LMStudioBackend.__init__` accepting `model_name=` and `base_url=` by keyword.
`functools.partial(LMStudioBackend, transport=httpx2.MockTransport(handler))`
would cover that.
##########
providers/common/ai/tests/unit/common/ai/utils/test_readiness_errors.py:
##########
@@ -0,0 +1,105 @@
+# 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 httpx2
+import pytest
+
+from airflow.providers.common.ai.utils.readiness_errors import (
+ extract_error_detail,
+ translate_readiness_errors,
+)
+
+ROOT = "http://localhost:1234"
+REQUEST = httpx2.Request("GET", f"{ROOT}/api/v1/models")
+
+
+def _response(status_code: int = 500, **kwargs) -> httpx2.Response:
+ return httpx2.Response(status_code, request=REQUEST, **kwargs)
+
+
+def _translate(**overrides):
+ kwargs = {
+ "server": "LM Studio",
+ "root": ROOT,
+ "timeout": 7.5,
+ "failure": "could not list models",
+ "timeout_failure": "timed out listing models",
+ }
+ return translate_readiness_errors(**{**kwargs, **overrides})
+
+
+class TestExtractErrorDetail:
+ def test_returns_the_error_field_when_it_is_a_non_empty_string(self):
+ assert extract_error_detail(_response(json={"error": "model not
found"})) == "model not found"
+
+ @pytest.mark.parametrize(
+ ("kwargs", "expected"),
+ [
+ pytest.param({"json": {"error": ""}}, '{"error":""}',
id="empty-error"),
+ pytest.param({"json": {"error": {"message": "x"}}},
'{"error":{"message":"x"}}', id="non-string"),
+ pytest.param({"json": {"other": "x"}}, '{"other":"x"}',
id="no-error-key"),
+ pytest.param({"json": ["a"]}, '["a"]', id="non-dict-body"),
+ pytest.param({"content": b" plain text "}, "plain text",
id="not-json-stripped"),
+ ],
+ )
+ def test_falls_back_to_the_stripped_body(self, kwargs, expected):
+ assert extract_error_detail(_response(**kwargs)) == expected
+
+ def test_cuts_the_body_to_200_characters(self):
+ assert extract_error_detail(_response(content=b"x" * 500)) == "x" * 200
+
+ def test_falls_back_to_the_reason_phrase_when_the_body_is_empty(self):
+ assert extract_error_detail(_response(503)) == "Service Unavailable"
+
+
+class TestTranslateReadinessErrors:
+ def test_passes_through_when_nothing_is_raised(self):
Review Comment:
This has no assertion, and every other test in the class goes through the
same `yield`, so it can't fail on anything they wouldn't catch. Drop it?
##########
providers/common/ai/tests/unit/common/ai/hooks/test_lmstudio.py:
##########
@@ -0,0 +1,302 @@
+# 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
+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"]
+
+ def test_model_missing_from_the_list_is_still_loaded(self):
+ methods: list[str] = []
+
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ methods.append(request.method)
+ if request.method == "GET":
+ return _build_models_response(loaded=True, key="another")
+ return httpx2.Response(200, json={"status": "loaded"})
+
+ _build_backend(handler).load(timeout=5.0)
+
+ assert methods == ["GET", "POST"]
+
+ 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": "model 'qwen3' not
found"})
+
+ 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"
+ )
+ 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_model_entry_without_expected_fields_counts_as_not_loaded(self):
+ methods: list[str] = []
+
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ methods.append(request.method)
+ if request.method == "GET":
+ return httpx2.Response(200, json={"models": [{"type": "llm"},
{"key": "qwen3"}]})
+ return httpx2.Response(200, json={"status": "loaded"})
+
+ _build_backend(handler).load(timeout=5.0)
+
+ assert methods == ["GET", "POST"]
+
+ @pytest.mark.parametrize(
+ "loaded_instances",
+ [
+ pytest.param(None, id="null"),
+ pytest.param("loaded", id="string"),
+ pytest.param({"id": "qwen3"}, id="object"),
+ pytest.param(1, id="integer"),
+ pytest.param(True, id="boolean"),
+ ],
+ )
+ def test_loaded_instances_that_is_not_a_list_counts_as_not_loaded(self,
loaded_instances):
+ methods: list[str] = []
+
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ methods.append(request.method)
+ if request.method == "GET":
+ return httpx2.Response(
+ 200, json={"models": [{"key": "qwen3", "loaded_instances":
loaded_instances}]}
+ )
+ return httpx2.Response(200, json={"status": "loaded"})
+
+ _build_backend(handler).load(timeout=5.0)
+
+ assert methods == ["GET", "POST"]
+
+ @pytest.mark.parametrize(
+ ("response", "expected_detail"),
+ [
+ pytest.param(
+ httpx2.Response(502, text="<html>Bad Gateway</html>"),
+ "<html>Bad Gateway</html>",
+ id="non-json-body",
+ ),
+ pytest.param(
+ httpx2.Response(500, text='{"message": "boom"}'),
+ '{"message": "boom"}',
+ id="json-without-error",
+ ),
+ pytest.param(httpx2.Response(500, text="x" * 500), "x" * 200,
id="long-body-truncated"),
+ pytest.param(httpx2.Response(500), "Internal Server Error",
id="empty-body"),
+ ],
+ )
+ def test_http_error_falls_back_to_body_text(self, response,
expected_detail):
Review Comment:
These cases repeat `TestExtractErrorDetail` in `test_readiness_errors.py`
one for one, and `test_list_error_says_listing_failed_not_loading` already
checks the list-step wording. Can this one go?
##########
providers/common/ai/tests/unit/common/ai/utils/test_readiness_errors.py:
##########
@@ -0,0 +1,105 @@
+# 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 httpx2
+import pytest
+
+from airflow.providers.common.ai.utils.readiness_errors import (
+ extract_error_detail,
+ translate_readiness_errors,
+)
+
+ROOT = "http://localhost:1234"
+REQUEST = httpx2.Request("GET", f"{ROOT}/api/v1/models")
+
+
+def _response(status_code: int = 500, **kwargs) -> httpx2.Response:
Review Comment:
Nit: `_build_response`, to match `_build_backend` and
`_build_models_response` in `test_lmstudio.py`?
##########
providers/common/ai/src/airflow/providers/common/ai/hooks/lmstudio.py:
##########
@@ -0,0 +1,138 @@
+# 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
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 LM Studio.
+ :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 the server cannot be reached, or a request
exceeds the time it was given
+ (see the class docstring).
+ :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.
+ """
+ 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._is_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,
Review Comment:
`remaining` is a raw float, so a load that times out prints every digit of
it in the message, fifteen-odd decimal places. Could the helper format the
number (`{timeout:.1f}`)?
--
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]