| #!/usr/bin/env -S uv run --script | |
| # 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. | |
| """Standalone / ASGI entrypoint for llmao (Apache STeVe-style). | |
| Loads config.yaml next to this file, serves with optional TLS from certs/, | |
| and uses asfquart OAuth so redirect URIs work with localhost.apache.org. | |
| cp config.yaml.example config.yaml # then edit secrets | |
| # generate PEMs under certs/ — see certs/README.md | |
| uv run python main.py | |
| # ASGI (e.g. Hypercorn): | |
| # uv run python -m hypercorn main:llmao_app | |
| """ | |
| from __future__ import annotations | |
| import functools | |
| import logging | |
| import pathlib | |
| import sys | |
| import yaml | |
| from hypercorn.middleware import ProxyFixMiddleware | |
| _LOGGER = logging.getLogger(__name__) | |
| # Year, seconds and the UTC offset. Correlating a portal line with an Apache | |
| # error log, a journald entry and the gateway's own log needs all three: minutes | |
| # alone put eight events in one bucket, and no year makes a January file | |
| # ambiguous. ISO-8601 order so a sort is chronological. | |
| DATE_FORMAT = "%Y-%m-%d %H:%M:%S%z" | |
| THIS_DIR = pathlib.Path(__file__).resolve().parent | |
| CERTS_DIR = THIS_DIR / "certs" | |
| # Populated by run_asgi() for Hypercorn: ``main:llmao_app`` | |
| llmao_app = None | |
| def create_app(): | |
| """Create the asfquart app; pages/api register routes on import.""" | |
| if str(THIS_DIR) not in sys.path: | |
| sys.path.insert(0, str(THIS_DIR)) | |
| import asfquart | |
| import asfquart.generics | |
| # Pin classic oauth.apache.org URLs (same pattern as Apache STeVe). | |
| asfquart.generics.OAUTH_URL_INIT = "https://oauth.apache.org/auth?state=%s&redirect_uri=%s" | |
| asfquart.generics.OAUTH_URL_CALLBACK = "https://oauth.apache.org/token?code=%s" | |
| app = asfquart.construct( | |
| "llmao", | |
| app_dir=str(THIS_DIR), | |
| static_folder=None, # /static served from pages.py | |
| oauth=True, | |
| force_login=True, | |
| ) | |
| # Fail-fast: models.yaml is required (same presumption as config.yaml). | |
| from llmao import actions, prompt_log | |
| from llmao.auth import make_token_handler | |
| from llmao.capacity import ( | |
| CapacityPruner, | |
| CapacityStore, | |
| CapacityWriter, | |
| DemandRollup, | |
| HourlyRollup, | |
| retention_days, | |
| ) | |
| from llmao.fleet import Fleet, validate_fleet | |
| # Config is app.cfg (EasyDict from config.yaml) — dotted access throughout. | |
| from llmao.models import load_models | |
| from llmao.provisioning import ProvisioningRecord | |
| from llmao.proxy.client import LiteLLMBackend | |
| from llmao.pruner import Pruner | |
| from llmao.sampler import MetricsSampler, sample_interval | |
| from llmao.seam import Seam | |
| definitions = load_models(cfg=app.cfg) | |
| validate_fleet(app.cfg, models=definitions) | |
| # The model definitions, loaded and validated once. Beside app.cfg: the | |
| # pages and the config route read them here; the fleet is built from the | |
| # same list. Nothing reads models.yaml again. | |
| app.models = definitions | |
| # Required, and checked before anything starts. | |
| interval = sample_interval(app.cfg) | |
| keep_days = retention_days(app.cfg) | |
| action_days = actions.retention_days(app.cfg) | |
| # Every config fetch, by the name the rental sent (llmao/provisioning.py). | |
| # One record: the config route writes it, the fleet reads it each pass. | |
| app.provisioning = ProvisioningRecord() | |
| fleet = Fleet.from_cfg(app.cfg, models=definitions, provisioning=app.provisioning) | |
| backend = LiteLLMBackend(app.cfg, fleet) | |
| fleet.after_probe = backend.deployments.sync_selfhost | |
| app.fleet = fleet | |
| app.add_runner(fleet.run_lifecycle, name="fleet-lifecycle") | |
| app.add_runner(fleet.run_runpod_rentals, name="runpod-rentals") | |
| app.add_runner(backend.run_skew, name="litellm-skew") | |
| app.add_runner(backend.watch_outside_edits, name="litellm-outside-edits") | |
| # Capacity: what each rental did, hour by hour (docs/capacity-design.md). | |
| # The sampler reads every rental's /metrics and feeds the rollup; the writer | |
| # stores finished hours in LiteLLM, apart from the sampler so a slow | |
| # LiteLLM cannot stall the readings; the pruner drops old days. | |
| rollup = HourlyRollup(interval_s=interval) | |
| app.capacity = CapacityStore(backend.memory) | |
| app.add_runner(MetricsSampler(fleet, rollup, interval_s=interval).run, name="metrics-sampler") | |
| app.add_runner(CapacityWriter(rollup, app.capacity).run, name="capacity-writer") | |
| app.add_runner(CapacityPruner(app.capacity, keep_days).run, name="capacity-prune") | |
| # Demand: what was asked, per model per hour, from LiteLLM's spend log, | |
| # rolled up once a day for each closed day (docs/prompt-logging-design.md). | |
| app.add_runner( | |
| DemandRollup( | |
| backend.metering, app.capacity, keep_days, log_dir=prompt_log.log_dir(app.cfg), notices=backend.log | |
| ).run, | |
| name="demand-rollup", | |
| ) | |
| # Daily pruning of the other records kept in LiteLLM's memory store. Each | |
| # line is one kind of record and its store's own rule; this list is the | |
| # one place that says what is pruned. | |
| app.actions = actions.ActionLog(backend.memory) | |
| pruner = Pruner( | |
| [ | |
| ("requests", backend.requests.prune), | |
| ("actions", functools.partial(app.actions.prune, keep_days=action_days)), | |
| ] | |
| ) | |
| app.add_runner(pruner.run, name="memory-prune") | |
| seam = Seam(app.cfg, backend) | |
| app.token_handler = make_token_handler(app.cfg) | |
| app.seam = seam | |
| app.backend = backend | |
| # The 500 handler (JSON under /v1/, a flash and the home page elsewhere) | |
| # is registered in pages.py. | |
| @app.before_serving | |
| async def _warm_backend(): | |
| # Fail-fast if LiteLLM is down (puppet starts proxy first; local: make proxy). | |
| await backend.warm() | |
| _LOGGER.info( | |
| "LiteLLM team cache warmed (%d project→team_id mappings)", | |
| len(backend.teams), | |
| ) | |
| @app.after_serving | |
| async def _close_backend(): | |
| await backend.aclose() | |
| # Register routes (decorators bind to asfquart.APP). | |
| import api # noqa: F401 | |
| import pages # noqa: F401 | |
| return app | |
| def _log_level(default: int = logging.DEBUG) -> int: | |
| """The level named by config.yaml's `log_level`. | |
| The default is DEBUG because that is what this module did before the | |
| setting existed: deploying a config that happens to say nothing should | |
| not quieten a running host. Puppet names the level explicitly, and INFO | |
| is the right steady state for a gateway that sees every prompt's | |
| surroundings -- but that choice belongs in the node yaml, not here. | |
| Read from the file rather than from app.cfg because logging is set up | |
| before asfquart loads the config, and a level that only took effect once | |
| the app came up would miss the noisy part. | |
| A missing or unreadable config is not this function's problem to report: | |
| run_standalone checks for the file a few lines on and says so properly, | |
| and under Puppet the file is there before the service starts. | |
| """ | |
| try: | |
| loaded = yaml.safe_load((THIS_DIR / "config.yaml").read_text()) or {} | |
| except (OSError, yaml.YAMLError): | |
| return default | |
| if not isinstance(loaded, dict): | |
| return default | |
| name = str(loaded.get("log_level") or "").strip().upper() | |
| if not name: | |
| return default | |
| # getLevelNamesMapping holds only level names, so a typo gets None rather | |
| # than something that is not a level at all. NOTSET is the exception | |
| # worth refusing: it is in there as 0, which on the root logger means log | |
| # EVERYTHING -- louder than DEBUG, and the opposite of what whoever wrote | |
| # it in the node yaml meant. | |
| level = logging.getLevelNamesMapping().get(name) | |
| if level is None or name == "NOTSET": | |
| # Before basicConfig, so this goes out through logging.lastResort to | |
| # stderr and into journald. Worth saying: a silent fallback on a typo | |
| # is how a host ends up logging at a level nobody chose. | |
| _LOGGER.warning("config.yaml: log_level=%r is not a level; using %s", name, logging.getLevelName(default)) | |
| return default | |
| return level | |
| def _configure_logging(): | |
| level = _log_level() | |
| # NOTE: no-op if Hypercorn has set up the root logger. | |
| logging.basicConfig( | |
| level=level, | |
| style="{", | |
| format="[{asctime}|{levelname}|{name}] {message}", | |
| datefmt=DATE_FORMAT, | |
| ) | |
| # We don't want DEBUG messages from these modules. | |
| for modname in { | |
| "selector_events", | |
| "hpack", | |
| "sslproto", | |
| "asyncio", | |
| "httpcore.http11", | |
| "httpcore.connection", | |
| "watchfiles.main", | |
| }: | |
| logging.getLogger(modname).setLevel(logging.INFO) | |
| # Regardless of the root logger, this module follows the configured level. | |
| # It used to be pinned to DEBUG, which meant there was no setting that | |
| # could quieten it. | |
| _LOGGER.setLevel(level) | |
| def run_standalone() -> None: | |
| """Run as a standalone server (asfquart runx + optional TLS).""" | |
| _configure_logging() | |
| _LOGGER.info(" ** Run-mode: Standalone") | |
| if not (THIS_DIR / "config.yaml").is_file(): | |
| _LOGGER.error("Missing config.yaml next to main.py. Copy config.yaml.example to config.yaml and edit secrets.") | |
| sys.exit(1) | |
| app = create_app() | |
| kwargs = {} | |
| server = getattr(app.cfg, "server", None) or {} | |
| port = int(getattr(server, "port", None) or (server.get("port") if hasattr(server, "get") else None) or 8443) | |
| certfile = getattr(server, "certfile", None) | |
| keyfile = getattr(server, "keyfile", None) | |
| if isinstance(server, dict): | |
| certfile = server.get("certfile") or certfile | |
| keyfile = server.get("keyfile") or keyfile | |
| extra_files = set() | |
| if certfile and keyfile: | |
| cert_path = pathlib.Path(certfile) | |
| key_path = pathlib.Path(keyfile) | |
| if not cert_path.is_absolute(): | |
| cert_path = CERTS_DIR / cert_path | |
| if not key_path.is_absolute(): | |
| key_path = CERTS_DIR / key_path | |
| kwargs["certfile"] = str(cert_path) | |
| kwargs["keyfile"] = str(key_path) | |
| extra_files.update((cert_path, key_path)) | |
| _LOGGER.info("TLS enabled: cert=%s key=%s", cert_path, key_path) | |
| else: | |
| _LOGGER.info("TLS disabled (no server.certfile/keyfile); plain HTTP") | |
| extra_files.add(THIS_DIR / "config.yaml") | |
| app.runx(port=port, extra_files=extra_files, **kwargs) | |
| # One reverse proxy: the Apache vhost, over loopback. ProxyFixMiddleware | |
| # reads the entry that many places from the RIGHT of X-Forwarded-For, which | |
| # is the one Apache appended itself -- so a client that sends its own | |
| # X-Forwarded-For only adds an entry to the left of it and cannot choose the | |
| # address we record. | |
| TRUSTED_HOPS = 1 | |
| def run_asgi() -> None: | |
| """Run as an ASGI process (e.g. Hypercorn imports main:llmao_app).""" | |
| _configure_logging() | |
| _LOGGER.info(" ** Run-mode: ASGI") | |
| global llmao_app | |
| # Wrapped only here. Standalone serves the Quart app directly and has no | |
| # proxy in front of it, so there is nothing to correct and nothing that | |
| # should be trusted if a header turned up. | |
| llmao_app = ProxyFixMiddleware(create_app(), trusted_hops=TRUSTED_HOPS) | |
| if __name__ == "__main__": | |
| # $ uv run python main.py | |
| run_standalone() | |
| else: | |
| # Using Hypercorn: | |
| # | |
| # $ uv run python -m hypercorn main:llmao_app | |
| # | |
| # NOTE: without our extended shutdown_trigger, we cannot reload | |
| # or restart on .py changes, extra_files changes, or respond to | |
| # SIGUSR2 to restart. Hypercorn will respond to SIGTERM/SIGINT | |
| # and shutdown. | |
| run_asgi() |