Lee-W commented on code in PR #76802:
URL: https://github.com/apache/airflow/pull/76802#discussion_r4696092275


##########
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:
   `ConnectError` is re-raised with the server and root in the message, and the 
`load()` docstrings no longer promise `TimeoutError`.



##########
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:
   Both timeout messages in the helper now use `{timeout:.1f}`.



##########
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:
   The example now follows the first paragraph, with the caveats after it as 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]

Reply via email to