kaxil commented on code in PR #76802: URL: https://github.com/apache/airflow/pull/76802#discussion_r4696915733
########## providers/common/ai/docs/self_hosted_models.rst: ########## @@ -317,9 +317,9 @@ replicas behind a load balancer, the load request can reach a different server than the LLM call, and then it has no effect on that call. ``timeout`` is passed as is to the load request. Running out ends in a -``TimeoutError`` naming the model, or the server when it cannot be reached. -Nothing is retried, so a wrong host, a server error or a request timing out is -raised right away. +``TimeoutError`` naming the model. A server that cannot be reached raises +``httpx2.ConnectError`` naming the server. Nothing is retried, so a wrong host, Review Comment: A host that drops packets ends in `httpx2.ConnectTimeout`, which isn't a `ConnectError`, so that case still raises `TimeoutError` naming the server, not the model. Could this say a refused connection raises `httpx2.ConnectError` and a connect timeout raises `TimeoutError`, both naming the server? ########## 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 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. + """ + 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, + 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 _is_model_loaded(self, client: httpx2.Client, *, timeout: float) -> bool: + """Return whether the model's entry in the model list has a loaded instance.""" + response = client.get(f"{self.root}{_LIST_MODELS_PATH}", timeout=timeout) + response.raise_for_status() + models = self._extract_models(response) + return any( + m.get("key") == self.model_name Review Comment: I missed this earlier, sorry. LM Studio's chat endpoint also accepts names that aren't the listed `key`, like `Qwen/Qwen3-0.6B` or the short `qwen3-0.6b` its own error message suggests, and with one of those this never matches, so every `ensure_model_ready` call loads another copy. On a real LM Studio, three calls per name left three extra ~800 MB instances with no TTL, and the ones loaded under the short name don't show up in `GET /api/v1/models` at all. Could this raise `ValueError` naming the listed keys when nothing matches, instead of loading? The LM Studio line near the top of the docs page ("the model identifier shown for whatever you loaded in its UI") also points people at those other names. -- 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]
