diff --git a/cli/administration/deploy/development/env.py b/cli/administration/deploy/development/env.py index d2f9a923a1..23d467b9b5 100644 --- a/cli/administration/deploy/development/env.py +++ b/cli/administration/deploy/development/env.py @@ -8,6 +8,7 @@ VALID_DISTROS: tuple[str, ...] = distro_names() TOOLS_LANE_KEYS: tuple[str, ...] = ( "INFINITO_TOOLS_LIBRETRANSLATE_PORT", + "INFINITO_TOOLS_LITELLM_PORT", "INFINITO_TOOLS_MODELS_HOST_PATH", "INFINITO_TOOLS_S1_PORT", "INFINITO_TOOLS_TRANSLATE_PORT", diff --git a/compose/tools.override.yml b/compose/tools.override.yml index fdb49d32b0..7f7b735dfa 100644 --- a/compose/tools.override.yml +++ b/compose/tools.override.yml @@ -52,6 +52,8 @@ services: .env single source of truth}:${INFINITO_TOOLS_TRANSLATE_PORT:?Run 'make dotenv' to generate the .env single source of truth}" - "${INFINITO_BIND_IP:?Run 'make dotenv' to generate the .env single source of truth}:${INFINITO_TOOLS_S1_PORT:?Run 'make dotenv' to generate the .env single source of truth}:${INFINITO_TOOLS_S1_PORT:?Run 'make dotenv' to generate the .env single source of truth}" + - "${INFINITO_BIND_IP:?Run 'make dotenv' to generate the .env single source of truth}:${INFINITO_TOOLS_LITELLM_PORT:?Run 'make dotenv' to generate the + .env single source of truth}:${INFINITO_TOOLS_LITELLM_PORT:?Run 'make dotenv' to generate the .env single source of truth}" networks: default: diff --git a/inventories/development/tools.yml.j2 b/inventories/development/tools.yml.j2 index 16c7829eb5..d8df933297 100644 --- a/inventories/development/tools.yml.j2 +++ b/inventories/development/tools.yml.j2 @@ -32,6 +32,14 @@ applications: cpus: "{{ lookup('resource', 'host_cpus') }}" mem_limit: "{{ lookup('resource', 'mem_limit') }}" pids_limit: 4096 + svc-ai-litellm: + secrets: + credentials: + master_key: [[ litellm_master_key ]] + svc-ai-ollama: + services: + ollama: + cpus: "{{ lookup('resource', 'host_cpus') }}" svc-ai-s1: secrets: credentials: @@ -39,3 +47,8 @@ applications: services: s1: models_dir: [[ models_dir ]]/s1 + web-svc-translate: + services: + translate: + router: + strategy: preference diff --git a/tests/oracle/test_translation_score.py b/tests/oracle/test_translation_score.py index 3236836d0f..36262b04e2 100644 --- a/tests/oracle/test_translation_score.py +++ b/tests/oracle/test_translation_score.py @@ -50,7 +50,7 @@ from utils.i18n.judge import MIDDLE, ChatJudge from utils.i18n.languages import DOMAINS, domain_languages, load_languages from utils.i18n.libretranslate import SERVICE_KEY from utils.i18n.spans import prose -from utils.inventory.tools import LIBRETRANSLATE_ROLE, lane_url +from utils.inventory.tools import LIBRETRANSLATE_ROLE, LITELLM_KEY, lane_url from utils.roles.mapping import ROLE_FILE_META_SERVICES from . import PROJECT_ROOT, SUITE @@ -100,16 +100,12 @@ class TestTranslationScore(unittest.TestCase): def setUpClass(cls): cls.base = lane_url(PROJECT_ROOT, JUDGE_ROLE, JUDGE_SERVICE_KEY) cls.engine = lane_url(PROJECT_ROOT, LIBRETRANSLATE_ROLE, SERVICE_KEY) - for url in (f"{cls.base}/health", f"{cls.engine}/languages"): + for url in (f"{cls.base}/health/liveliness", f"{cls.engine}/languages"): if not serves(url): raise unittest.SkipTest( f"nothing answers on {url}. `make test-oracle` brings the " "tools lane up before the suite runs, and this check cannot " - f"deploy it from inside the stack's container. The lane's " - f"default roles are the translation engine and System One " - f"(utils/inventory/tools.py, default_roles), so {JUDGE_ROLE} " - "and the model server behind it are not among them and this " - "check stays skipped until they are." + "deploy it from inside the stack's container." ) _progress(SUITE, f"the judge answers on {cls.base}") @@ -151,7 +147,7 @@ class TestTranslationScore(unittest.TestCase): client = LibreTranslate(self.engine, ENGINE_WORKERS) available = client.targets() - judge = ChatJudge(self.base, _model()) + judge = ChatJudge(self.base, _model(), api_key=LITELLM_KEY) languages = load_languages(PROJECT_ROOT) verdicts: dict[str, str] = {} offenders: list[str] = [] diff --git a/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py b/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py index edc768191c..9bf85a96d5 100644 --- a/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py +++ b/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py @@ -30,6 +30,7 @@ _LOCAL_PRIMARY = { "INFINITO_PUBLISH_PORTS": "", "INFINITO_GPU_COUNT": "0", "INFINITO_TOOLS_LIBRETRANSLATE_PORT": "8097", + "INFINITO_TOOLS_LITELLM_PORT": "8081", "INFINITO_TOOLS_MODELS_HOST_PATH": "/var/cache/infinito/core/cache/models", "INFINITO_TOOLS_S1_PORT": "8096", "INFINITO_TOOLS_TRANSLATE_PORT": "8101", diff --git a/utils/env/handlers/__init__.py b/utils/env/handlers/__init__.py index f4aec5c164..bb368829e8 100644 --- a/utils/env/handlers/__init__.py +++ b/utils/env/handlers/__init__.py @@ -63,6 +63,7 @@ from .infinito.running_on import github as running_on_github from .infinito.swarm_nfs import export_base as swarm_nfs_export_base from .infinito.swarm_nfs import state_path as swarm_nfs_state_path from .infinito.tools import libretranslate as tools_libretranslate +from .infinito.tools import litellm as tools_litellm from .infinito.tools import models as tools_models from .infinito.tools import s1 as tools_s1 from .infinito.tools import translate as tools_translate @@ -119,6 +120,7 @@ ORDERED_HANDLERS = [ git_identity, gpu_count, tools_libretranslate, + tools_litellm, tools_models, tools_s1, tools_translate, diff --git a/utils/env/handlers/infinito/tools/litellm.py b/utils/env/handlers/infinito/tools/litellm.py new file mode 100644 index 0000000000..9dead26eb2 --- /dev/null +++ b/utils/env/handlers/infinito/tools/litellm.py @@ -0,0 +1,29 @@ +"""INFINITO_TOOLS_LITELLM_PORT: loopback port the tools runner forwards +to its model gateway, read from roles/svc-ai-litellm/meta/services.yml.""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING + +from utils.cache.files import read_text +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +if TYPE_CHECKING: + from utils.env.builder import BuildContext, EnvBuilder + +KEY = "INFINITO_TOOLS_LITELLM_PORT" +COMMENT = "Loopback port the tools runner forwards to its model gateway." +SERVICES = f"roles/svc-ai-litellm/{ROLE_FILE_META_SERVICES}" +HTTP_PORT = re.compile( + r"^litellm:\n(?:.*\n)*?\s+local:\n\s+http:\s*(\d+)\s*$", re.MULTILINE +) + + +def apply(eb: EnvBuilder, ctx: BuildContext) -> None: + services = ctx.repo_root / SERVICES + if not services.is_file(): + return + found = HTTP_PORT.search(read_text(services)) + if found: + eb.setdefault(KEY, found.group(1), comment=COMMENT) diff --git a/utils/inventory/tools.py b/utils/inventory/tools.py index 2809dcf1d0..ae38df1e97 100644 --- a/utils/inventory/tools.py +++ b/utils/inventory/tools.py @@ -25,6 +25,11 @@ or passing a secret on a command line. It is a fixed literal because the lane serves the repository's own tooling on a developer machine and reaches no deployment that holds data, the same standing as the dummy authorized key the template already carries. Never reuse it anywhere a real caller could reach. + +:data:`LITELLM_KEY` pins the model gateway's master key for the same reason +and under the same standing. A deployment hands each consumer a virtual key +instead, which is what the role's secret description asks for; the oracle +judge is not a deployed consumer and has no vault to read one from. """ from __future__ import annotations @@ -42,9 +47,14 @@ TEMPLATE = Path("inventories") / "development" / "tools.yml.j2" RENDERED = Path("inventories") / "development" / "tools.rendered.yml" ADDRESS = Path("inventories") / "development" / "tools.address" API_KEY = "toolsLaneTestKeyNotASecret0000000000" +LITELLM_KEY = "toolsLaneLiteLlmMasterKeyNotASecret000000000000000000" LIBRETRANSLATE_ROLE = "svc-ai-libretranslate-engine" S1_ROLE = "svc-ai-s1" +LITELLM_ROLE = "svc-ai-litellm" +OLLAMA_ROLE = "svc-ai-ollama" +GATEWAY_ROLE = "web-svc-translate" LANE_SERVICE = "tools" +LOCAL_MODELS_FILE = Path("group_vars") / "all" / "16_ai.yml" PROBE_TIMEOUT_SECONDS = 10 @@ -170,17 +180,26 @@ def host_url(root: Path, role: str, service_key: str) -> str: return f"http://{environment(root)['INFINITO_BIND_IP']}:{port}" -def _answers(url: str) -> bytes | None: +def _answers(url: str, api_key: str = "") -> bytes | None: """Return what ``url`` served, or None when it did not answer. Args: url: absolute URL to read. + api_key: sent as a bearer token, for a route that authenticates its + callers. A 401 reads as no answer, which is what it means here: + the service is up but holds a key the checks cannot use, and a + lane in that state has to be deployed again rather than reused. """ import urllib.error import urllib.request + request = urllib.request.Request(url) # noqa: S310 - the URL is this repository's own service definition + if api_key: + request.add_header("Authorization", f"Bearer {api_key}") try: - with urllib.request.urlopen(url, timeout=PROBE_TIMEOUT_SECONDS) as response: # noqa: S310 - the URL is this repository's own service definition + with urllib.request.urlopen( # noqa: S310 - the URL is this repository's own service definition + request, timeout=PROBE_TIMEOUT_SECONDS + ) as response: return response.read() except (urllib.error.URLError, OSError, ValueError): return None @@ -199,6 +218,77 @@ def _base_subtag(code: str) -> str: return code.split("-", 1)[0].strip().lower() +def _litellm_serves_the_named_model(root: Path) -> bool: + """Return whether the model gateway answers with the catalogue's model. + + Reachability is not enough twice over. The route authenticates, so a + gateway holding a key these checks cannot use looks healthy from outside + and refuses every call they make. And a lane brought up before + ``AI_LOCAL_MODELS`` named a different model keeps serving the old one, + which no probe of liveliness can see. + + Args: + root: repository root. + """ + import json + + alias = _named_model(root) + body = _answers(f"{host_url(root, LITELLM_ROLE, 'litellm')}/models", LITELLM_KEY) + if body is None or not alias: + return False + try: + served = {entry.get("id") for entry in json.loads(body).get("data") or []} + except (ValueError, AttributeError, TypeError): + return False + return alias in served + + +def _named_model(root: Path) -> str: + """Return the alias the lane's model server is expected to serve. + + Args: + root: repository root. + """ + models = load_yaml(root / LOCAL_MODELS_FILE).get("AI_LOCAL_MODELS") or [] + first = models[0] if models else {} + return str(first.get("alias") or "") if isinstance(first, dict) else "" + + +def _gateway_covers_the_catalogs(root: Path) -> bool: + """Return whether the gateway offers every language the catalogs name. + + A gateway that answers is not a gateway that routes: its ``/languages`` + is the union over its backends, so one whose chat backend declares no + pairs advertises the engine's 47 codes and nothing else. The translation + run waits on exactly this list, so a lane left in that state is not + serving however healthy each container looks. + + Args: + root: repository root. + """ + import json + + from utils.i18n.languages import ( + DOMAINS, + SOURCE_LANGUAGE, + domain_languages, + load_languages, + ) + + body = _answers(f"{host_url(root, GATEWAY_ROLE, 'translate')}/languages") + if body is None: + return False + try: + served = { + entry["code"]: set(entry["targets"]) for entry in json.loads(body) + }.get(SOURCE_LANGUAGE, set()) + except (ValueError, KeyError, TypeError): + return False + languages = load_languages(root) + wanted = {code for domain in DOMAINS for code in domain_languages(languages, domain)} + return wanted <= served + + def serving(root: Path, load_only: list[str], roles: tuple[str, ...]) -> bool: """Return whether every lane role asked for already answers. @@ -222,6 +312,10 @@ def serving(root: Path, load_only: list[str], roles: tuple[str, ...]) -> bool: if S1_ROLE in roles and _answers(f"{host_url(root, S1_ROLE, 's1')}/health") is None: return False + if LITELLM_ROLE in roles and not _litellm_serves_the_named_model(root): + return False + if GATEWAY_ROLE in roles and not _gateway_covers_the_catalogs(root): + return False if LIBRETRANSLATE_ROLE not in roles: return True body = _answers( @@ -264,6 +358,7 @@ def render(root: Path, load_only: list[str]) -> Path: body = env.get_template(template_path.name).render( load_only=sorted(load_only), s1_api_key=API_KEY, + litellm_master_key=LITELLM_KEY, models_dir=models_dir(), ) rendered = root / RENDERED @@ -340,7 +435,13 @@ def main(argv: list[str] | None = None) -> int: from utils import PROJECT_ROOT from utils.i18n.libretranslate import baked_languages - default_roles = [LIBRETRANSLATE_ROLE, S1_ROLE] + default_roles = [ + LIBRETRANSLATE_ROLE, + S1_ROLE, + OLLAMA_ROLE, + LITELLM_ROLE, + GATEWAY_ROLE, + ] parser = argparse.ArgumentParser(description="Bring the tools lane up.") parser.add_argument("roles", nargs="*", default=default_roles) args = parser.parse_args(argv)