diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md index 16a25bb5..0a69c6f9 100644 --- a/.agents/AGENTS.md +++ b/.agents/AGENTS.md @@ -10,9 +10,9 @@ When working on this project, always refer to the dedicated **NotebookLM Compani - Local model benchmark metrics and `llama-server` configurations ### Notebook Details -- **Notebook Name:** `TriageGate-Architect-KB` +- **Notebook Name:** `LLM-Routing-KB` - **Notebook ID:** `llm-triage-gateway` -- **Notebook URL:** [TriageGate-Architect-KB](https://notebooklm.google.com/notebook/826cbd87-7969-4b0e-a38e-5517b5ab7d28) +- **Notebook URL:** [LLM-Routing-KB](https://notebooklm.google.com/notebook/826cbd87-7969-4b0e-a38e-5517b5ab7d28) ### How to Query Use the `notebooklm` MCP tools to search or ask questions about this codebase and stack: @@ -26,3 +26,61 @@ To prevent directory reorganization regressions, outdated file restorations, or 2. **Directory Rename Safety**: If Git reports conflicts related to moved directories or files, do not manually stage deletions of tracked files from moved directories (e.g., under the old `tests/` or `scripts/` paths) or re-create files at the root level. Resolve conflicts by directing all changes and file operations to the newly refactored paths. 3. **Verify Security Credentials**: Never accept resolutions that overwrite configuration files (`pod.yaml`, `start-stack.sh`) with hardcoded default passwords. Ensure placeholder-based configurations are preserved. 4. **Enforce Test Suite Count**: Run the full unit test suite (`pytest`) after conflict resolution. Verify that the total number of passing tests is equal to or greater than before the resolution. + +## Production Deployment Checklist + +Note: Throughout this checklist, the production host SSH alias is represented by `` (e.g., `boy`), the deployer home path is represented by `` (e.g., `/mnt/DATA/boy`), and the domain is represented by `` (e.g., `vendeuvre.lan`). + +### One-Time Host Prerequisites +- `net.ipv4.ip_unprivileged_port_start=80` persisted in `/etc/sysctl.d/99-unprivileged-ports.conf` +- Host firewall ports `80/tcp` and `443/tcp` opened in `firewalld` (e.g. `sudo firewall-cmd --zone=public --add-port=80/tcp --permanent && sudo firewall-cmd --zone=public --add-port=443/tcp --permanent && sudo firewall-cmd --reload`) +- SSH host alias configured in `~/.ssh/config` — use `ssh ` / `rsync ... :` throughout +- Required mount directories created under ``: + - `/.gemini/` + - `/.local/bin/agy` (copy of the `agy` binary) + - `/.local/share/goose/` + - `/.local/share/keyrings/` +- HAProxy SSL cert: `/haproxy/certs/.pem` +- HAProxy config: `/haproxy/haproxy.cfg` + +### Fresh Deploy Steps (after a PR is merged to master) +```bash +# 1. Clean up old deploy +ssh "rm -rf /LLM-Routing" + +# 2. Clone fresh from master +ssh "git clone https://github.com/sheepdestroyer/LLM-Routing.git /LLM-Routing" + +# 3. Start the full stack (builds and launches all containers) +ssh "cd /LLM-Routing && ./start-stack.sh --full-rebuild" + +# 4. Start (or restart) production HAProxy +ssh "podman rm -f production-haproxy || true" +ssh "podman run -d --name production-haproxy --restart always --net host \ + -v /haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro \ + -v /haproxy/certs:/usr/local/etc/haproxy/certs:ro \ + docker.io/library/haproxy:alpine" + +# 5. Start the host-side agy daemon +ssh "pkill -f host_agy_daemon.py || true" +ssh "nohup python3 /LLM-Routing/scripts/host_agy_daemon.py >/tmp/agy-daemon.log 2>&1 "curl -k -s --resolve .:443:127.0.0.1 https://./llm-routing/dashboard" | head -5 +``` + +### Notes +- The `agy-daemon.service` systemd unit cannot be reloaded via `systemctl --user` from + the agent terminal (DBus is not connected). Start the daemon manually with `nohup` as + shown above, or instruct the user to run it in their own session. +- **Sudo Password Precaution**: Always preserve exact bytes (including trailing spaces or newlines) when reading `~/.sudo_password` (e.g. `'your_password_here '`). Stripping whitespace will cause authentication to fail. +- `start-stack.sh` without `--full-rebuild` will do a fast pod restart (reuses images). + Use `--full-rebuild` after code changes or image updates. +- **GitHub CLI Authentication**: If running `gh` commands fails with a 401 error, ensure that `GITHUB_TOKEN` is exported (e.g., mapped from `GITHUB_MCP_PAT` in `~/.bashrc` via `export GITHUB_TOKEN="$GITHUB_MCP_PAT"`). + +## GitHub API & Operations Policy +When interacting with the GitHub API or performing repository/PR metadata operations: +1. **Prefer `gh` CLI**: Always prefer using the GitHub CLI (`gh`) instead of executing raw `curl` commands. +2. **REST API Fallback via `gh api`**: If standard `gh` commands (like `gh pr view`) fail due to missing GraphQL token scopes (e.g., `read:org`), use `gh api` to run REST queries against the endpoint (e.g., `gh api repos/{owner}/{repo}/pulls/{pr_number}/reviews`) as it does not require GraphQL scopes. diff --git a/README.md b/README.md index 5b45456a..20262cd8 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,7 @@ The gateway supports multiple routing modes controlled by the `model` field: All configurations, automation scripts, and databases are self-contained within this repository directory: ``` -/home/gpav/Vrac/LAB/AI/LLM-Routing/ +/path/to/LLM-Routing/ ├── .env # Environment file for API keys, passwords, and generated secrets (ignored by git) ├── .gitignore # Git ignore policy protecting secrets & database files ├── README.md # In-depth system and operational guide @@ -350,7 +350,7 @@ The stack also supports **semantic** (vector-similarity) caching via `vector_sto - **Embedding Model**: Zero-cost local `nomic-embed-text-v1.5-Q4_K_M` (~137MB GGUF) running on llama-server, loaded as `local-nomic-embed` in LiteLLM. Produces 768-dimension vectors with CLS pooling. - **Vector Store**: PostgreSQL with pgvector extension stores embeddings in the `litellm_semantic_cache` collection. - **Cost**: Completely free — no OpenRouter API calls for embedding generation. -- **Configuration**: The nomic-embed model profile in `models.ini` (`/home/gpav/Vrac/LAB/AI/models.ini`) includes `embedding = true`, `pooling = cls`, and `embd-normalize = 2` for proper vector similarity search. llama-server runs with `--models-max 3` to keep the classifier (0.8B), MoE (35B), and embedding model loaded simultaneously. +- **Configuration**: The nomic-embed model profile in `models.ini` (e.g., `/path/to/models.ini`) includes `embedding = true`, `pooling = cls`, and `embd-normalize = 2` for proper vector similarity search. llama-server runs with `--models-max 3` to keep the classifier (0.8B), MoE (35B), and embedding model loaded simultaneously. --- @@ -456,7 +456,7 @@ Uvicorn's log level follows the same env var via `${LOG_LEVEL:-warning}` in the | `PrivateTmp` | `yes` | Isolates `/tmp` namespace for the daemon | | `PrivateDevices` | `yes` | Restricts access to `/dev` (no raw disk/device access) | | `ProtectSystem` | `strict` | Makes `/usr` and `/etc` read-only | -| `ProtectHome` | `read-only` | `/home/gpav` is read-only except specific paths | +| `ProtectHome` | `read-only` | The user home directory is read-only except specific paths | | `ProtectKernelTunables` | `yes` | Makes `/sys` and `/proc/sys` read-only | | `ProtectKernelModules` | `yes` | Blocks loading or listing kernel modules | | `ProtectControlGroups` | `yes` | Makes cgroup filesystem read-only | @@ -758,7 +758,7 @@ To maximize throughput under concurrent queries, `llama-server` is configured wi #### 3. Custom Memory Endpoint Proxy & MCP Server To allow Goose (and other agents) to store, list, and delete persistent preference/factual memories, we implemented a custom memory stack: * **Triage Router Memory Proxy**: Exposes a catch-all route `@app.api_route("/v1/memory{path:path}", methods=["GET", "POST", "DELETE", "PUT"])` in `router/main.py` that intercepts memory calls and proxies them to the LiteLLM gateway (port 4000) using the securely-loaded `LITELLM_MASTER_KEY` authorization. -* **Memory MCP Bridge Server**: Created a custom stdio MCP server in [memory_mcp.py](file:///home/gpav/Vrac/LAB/AI/LLM-Routing/router/memory_mcp.py) that exposes the `rememberMemory`, `retrieveMemories`, and `removeSpecificMemory` tools. The script proxies these commands directly to `http://localhost:5000/v1/memory`. +* **Memory MCP Bridge Server**: Created a custom stdio MCP server in [memory_mcp.py](router/memory_mcp.py) that exposes the `rememberMemory`, `retrieveMemories`, and `removeSpecificMemory` tools. The script proxies these commands directly to `http://localhost:5000/v1/memory`. * **Goose Integration**: The built-in memory extension is disabled in `~/.config/goose/config.yaml` and replaced with the `litellm-memory` custom command-line extension running our bridge server. ## 9c. Ollama Proxy Integration (via LiteLLM ollama_chat) diff --git a/litellm/config.yaml b/litellm/config.yaml index d1043342..195712f5 100644 --- a/litellm/config.yaml +++ b/litellm/config.yaml @@ -38,29 +38,29 @@ litellm_settings: - agent-advanced-core - llm-routing-ollama - openrouter-auto - # - local-qwen-3.6 # DISABLED: 35B model unloaded (23GB GTT saved) + - local-qwen-3.6 - agent-medium-core: - agent-complex-core - agent-reasoning-core - agent-advanced-core - llm-routing-ollama - openrouter-auto - # - local-qwen-3.6 # DISABLED + - local-qwen-3.6 - agent-complex-core: - agent-reasoning-core - agent-advanced-core - llm-routing-ollama - openrouter-auto - # - local-qwen-3.6 # DISABLED + - local-qwen-3.6 - agent-reasoning-core: - agent-advanced-core - llm-routing-ollama - openrouter-auto - # - local-qwen-3.6 # DISABLED + - local-qwen-3.6 - agent-advanced-core: - llm-routing-ollama - openrouter-auto - # - local-qwen-3.6 # DISABLED + - local-qwen-3.6 model_list: - litellm_params: @@ -90,14 +90,13 @@ model_list: max_input_tokens: 524288 is_public_model_group: true -# DISABLED 2026-06-08 — 20GB on disk, 23GB GTT (system RAM as GPU buffer). -# Uncomment to re-enable once a lighter model replaces it. -#- litellm_params: -# api_base: http://127.0.0.1:8080/v1 -# api_key: local-token -# model: openai/qwen-35b-q4ks -# request_timeout: 300 -# model_name: local-qwen-3.6 +# Re-enabled 2026-07-08 — llama.cpp on port 8081, alias local-qwen-3.6 +- litellm_params: + api_base: http://127.0.0.1:8081/v1 + api_key: local-token + model: openai/local-qwen-3.6 + request_timeout: 300 + model_name: local-qwen-3.6 - litellm_params: api_base: http://127.0.0.1:8080/v1 api_key: local-token diff --git a/pod.yaml b/pod.yaml index fa8938ad..4541a55e 100644 --- a/pod.yaml +++ b/pod.yaml @@ -45,6 +45,10 @@ spec: value: LITELLM_MASTER_KEY_PLACEHOLDER - name: OLLAMA_API_KEY value: OLLAMA_API_KEY_PLACEHOLDER + - name: SERVER_ROOT_PATH + value: /llm-routing/litellm + - name: PROXY_BASE_URL + value: PROXY_BASE_URL_PLACEHOLDER image: ghcr.io/berriai/litellm:v1.91.0 livenessProbe: exec: @@ -62,7 +66,7 @@ spec: - python3 - -c - import urllib.request; urllib.request.urlopen('http://localhost:4000/health/readiness') - initialDelaySeconds: 10 + initialDelaySeconds: 45 periodSeconds: 10 timeoutSeconds: 5 volumeMounts: @@ -91,7 +95,7 @@ spec: - name: DATABASE_URL value: postgresql://postgres:POSTGRES_PASSWORD_ENCODED_PLACEHOLDER@127.0.0.1:5432/postgres - name: DBUS_SESSION_BUS_ADDRESS - value: unix:path=/run/user/1000/bus + value: unix:path=RUN_USER_PLACEHOLDER/bus - name: LITELLM_MASTER_KEY value: LITELLM_MASTER_KEY_PLACEHOLDER - name: LANGFUSE_PUBLIC_KEY @@ -102,6 +106,10 @@ spec: value: http://127.0.0.1:3001 - name: OLLAMA_API_KEY value: OLLAMA_API_KEY_PLACEHOLDER + - name: PUBLIC_BASE_URL + value: PUBLIC_BASE_URL_PLACEHOLDER + - name: ROUTING_DOMAIN + value: ROUTING_DOMAIN_PLACEHOLDER - name: LOG_LEVEL value: info image: localhost/llm-triage-router:latest @@ -140,11 +148,11 @@ spec: - mountPath: /usr/local/bin/agy name: agy-bin subPath: agy - - mountPath: /run/user/1000/bus + - mountPath: RUN_USER_PLACEHOLDER/bus name: dbus-socket - mountPath: /root/.local/share/keyrings name: keyring-store - - mountPath: /run/user/1000 + - mountPath: RUN_USER_PLACEHOLDER name: xdg-runtime - mountPath: /config/.env name: env-file @@ -427,48 +435,48 @@ spec: restartPolicy: Always volumes: - hostPath: - path: /home/gpav/Vrac/LAB/AI/LLM-Routing/valkey-data + path: WORKDIR_PLACEHOLDER/valkey-data name: valkey-storage - hostPath: - path: /home/gpav/Vrac/LAB/AI/LLM-Routing/litellm + path: WORKDIR_PLACEHOLDER/litellm name: litellm-config - hostPath: - path: /home/gpav/Vrac/LAB/AI/LLM-Routing/router + path: WORKDIR_PLACEHOLDER/router name: router-config - hostPath: - path: /home/gpav/Vrac/LAB/AI/LLM-Routing/postgres-data + path: WORKDIR_PLACEHOLDER/postgres-data name: postgres-storage - hostPath: - path: /home/gpav/Vrac/LAB/AI/LLM-Routing/clickhouse-data + path: WORKDIR_PLACEHOLDER/clickhouse-data name: clickhouse-storage - hostPath: - path: /home/gpav/Vrac/LAB/AI/LLM-Routing/redis-lf-data + path: WORKDIR_PLACEHOLDER/redis-lf-data name: redis-lf-storage - hostPath: - path: /home/gpav/Vrac/LAB/AI/LLM-Routing/minio-data + path: WORKDIR_PLACEHOLDER/minio-data name: minio-storage - hostPath: - path: /home/gpav/.gemini + path: HOME_PLACEHOLDER/.gemini name: gemini-secrets - hostPath: - path: /home/gpav/.local/share/goose + path: HOME_PLACEHOLDER/.local/share/goose name: goose-sessions - hostPath: - path: /home/gpav/.local/bin + path: HOME_PLACEHOLDER/.local/bin name: agy-bin - hostPath: - path: /run/user/1000/bus + path: RUN_USER_PLACEHOLDER/bus name: dbus-socket - hostPath: - path: /home/gpav/.local/share/keyrings + path: HOME_PLACEHOLDER/.local/share/keyrings name: keyring-store - hostPath: - path: /run/user/1000 + path: RUN_USER_PLACEHOLDER name: xdg-runtime - hostPath: - path: /home/gpav/Vrac/LAB/AI/LLM-Routing + path: WORKDIR_PLACEHOLDER name: env-file - hostPath: - path: /home/gpav/Vrac/LAB/AI/LLM-Routing/data + path: WORKDIR_PLACEHOLDER/data type: DirectoryOrCreate name: dataset-data diff --git a/router/agy_proxy.py b/router/agy_proxy.py index ffccd733..8c1f8631 100644 --- a/router/agy_proxy.py +++ b/router/agy_proxy.py @@ -42,7 +42,7 @@ async def save(self) -> None: logger = logging.getLogger("agy-proxy") -# In container: mounted from host /home/gpav/.local/bin/agy +# In container: mounted from host ~/.local/bin/agy AGY_BINARY = os.environ.get("AGY_BINARY_PATH", "/usr/local/bin/agy") if not os.path.exists(AGY_BINARY): AGY_BINARY = os.path.expanduser("~/.local/bin/agy") diff --git a/router/free_models_roster.json b/router/free_models_roster.json index 5f1dfe0c..8a71d4a5 100644 --- a/router/free_models_roster.json +++ b/router/free_models_roster.json @@ -42,6 +42,18 @@ "score": 28.0, "context_length": 256000 }, + { + "id": "tencent/hy3:free", + "name": "Tencent: Hy3 (free)", + "score": 25.0, + "context_length": 262144 + }, + { + "id": "poolside/laguna-xs-2.1:free", + "name": "Poolside: Laguna XS 2.1 (free)", + "score": 25.0, + "context_length": 262144 + }, { "id": "cohere/north-mini-code:free", "name": "Cohere: North Mini Code (free)", @@ -54,12 +66,7 @@ "score": 25.0, "context_length": 128000 }, - { - "id": "openrouter/owl-alpha", - "name": "Owl Alpha", - "score": 25.0, - "context_length": 1048756 - }, + { "id": "google/lyria-3-pro-preview", "name": "Google: Lyria 3 Pro Preview", @@ -139,6 +146,6 @@ "context_length": 32768 } ], - "updated_at": "2026-06-24T18:40:15.482014Z", - "count": 23 + "updated_at": "2026-07-08T22:55:47.271165Z", + "count": 24 } \ No newline at end of file diff --git a/router/main.py b/router/main.py index d8be6cfb..6324485e 100644 --- a/router/main.py +++ b/router/main.py @@ -18,14 +18,15 @@ from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse from fastapi.staticfiles import StaticFiles from pathlib import Path +from urllib.parse import urlparse from circuit_breaker import get_breaker from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator, RootModel from typing import Dict, Optional, Union +from urllib.parse import urlparse LITELLM_URL = (os.getenv("LITELLM_ADMIN_URL") or "http://127.0.0.1:4000").rstrip("/") -LLAMA_SERVER_URL = (os.getenv("LLAMA_SERVER_URL") or "http://127.0.0.1:8080").rstrip( - "/" -) +LLAMA_SERVER_URL = (os.getenv("LLAMA_SERVER_URL") or "http://127.0.0.1:8080").rstrip("/") +LANGFUSE_HOST = (os.getenv("LANGFUSE_HOST") or "http://127.0.0.1:3001").rstrip("/") GEMINI_OAUTH_CREDS_PATH = "/config/gemini_auth/oauth_creds.json" @@ -233,7 +234,7 @@ def get_langfuse(): _langfuse_client = langfuse.Langfuse( public_key=os.getenv("LANGFUSE_PUBLIC_KEY", ""), secret_key=os.getenv("LANGFUSE_SECRET_KEY", ""), - host=os.getenv("LANGFUSE_HOST", "http://127.0.0.1:3001"), + host=LANGFUSE_HOST, release="llm-triage-router-v1", ) logger.info("Langfuse client initialized") @@ -3069,9 +3070,102 @@ async def get_dashboard_stats(): return await get_dashboard_data() +def resolve_external_urls(request: Request) -> tuple[str, str, str]: + """Resolve and validate the base URLs for Langfuse, LiteLLM, and Llama.cpp.""" + # 1. Try to load centralized base URL from config/env + base_url_env = os.getenv("PUBLIC_BASE_URL") or os.getenv("BASEURL") or os.getenv("BASE_URL") + if base_url_env: + if "://" not in base_url_env: + parsed = urlparse(f"https://{base_url_env}") + else: + parsed = urlparse(base_url_env) + external_host = parsed.hostname or "localhost" + external_netloc = parsed.netloc or "localhost" + external_scheme = parsed.scheme if parsed.scheme in ("http", "https") else "https" + else: + external_host = request.base_url.hostname or "localhost" + external_netloc = request.base_url.netloc or "localhost" + external_scheme = request.url.scheme if request.url.scheme in ("http", "https") else "https" + + domain = os.getenv("ROUTING_DOMAIN") or "vendeuvre.lan" + + # Basic sanity-check on external_host, but don't over-restrict valid hostnames; + # fall back to the request base URL rather than silently forcing localhost. + if not isinstance(external_host, str) or not re.match(r"^[a-zA-Z0-9.-]+$", external_host): + logger.warning( + "Unexpected external_host %r, falling back to request.base_url.hostname (%r)", + external_host, + request.base_url.hostname, + ) + external_host = request.base_url.hostname or "localhost" + + # Relax external_netloc validation: use urlparse so IPv6 literals, IDN/punycode, + # and reverse-proxy-modified netlocs are supported. Log and fall back instead of + # silently forcing localhost when invalid. + if isinstance(external_netloc, str): + parsed_netloc = urlparse(f"{external_scheme}://{external_netloc}") + if not parsed_netloc.hostname: + logger.warning( + "Invalid external_netloc %r, falling back to request.base_url.netloc (%r)", + external_netloc, + request.base_url.netloc, + ) + external_netloc = request.base_url.netloc or "localhost" + else: + logger.warning( + "Non-string external_netloc %r, falling back to request.base_url.netloc (%r)", + external_netloc, + request.base_url.netloc, + ) + external_netloc = request.base_url.netloc or "localhost" + + # Enforce strict domain validation to prevent loose substring match bypasses (e.g., attacker-vendeuvre.lan) + is_valid_external = external_host == domain or external_host.endswith("." + domain) + is_valid_base = request.base_url.hostname == domain or (request.base_url.hostname or "").endswith("." + domain) + + if is_valid_external: + # Centralized base URL path under subdomain/reverse proxy + return ( + f"{external_scheme}://{external_netloc}/llm-routing/langfuse", + f"{external_scheme}://{external_netloc}/llm-routing/litellm/ui", + f"{external_scheme}://{external_netloc}/llm-routing/llama/" + ) + elif is_valid_base: + netloc = request.url.netloc if re.match(r"^[a-zA-Z0-9.-]+(?::\d+)?$", request.url.netloc) else "localhost" + base = f"{external_scheme}://{netloc}" + return ( + f"{base}/llm-routing/langfuse", + f"{base}/llm-routing/litellm/ui", + f"{base}/llm-routing/llama/" + ) + else: + # Local development fallback: derive ports and paths dynamically from configuration constants + parsed_lf = urlparse(LANGFUSE_HOST) + parsed_ll = urlparse(LITELLM_URL) + parsed_lm = urlparse(LLAMA_SERVER_URL) + + lf_port = f":{parsed_lf.port}" if parsed_lf.port else "" + ll_port = f":{parsed_ll.port}" if parsed_ll.port else "" + lm_port = f":{parsed_lm.port}" if parsed_lm.port else "" + + lf_path = parsed_lf.path + ll_path = parsed_ll.path or "/ui" + if not ll_path.endswith("/ui") and not ll_path.endswith("/ui/"): + ll_path = ll_path.rstrip("/") + "/ui" + lm_path = parsed_lm.path + + return ( + f"http://{external_host}{lf_port}{lf_path}", + f"http://{external_host}{ll_port}{ll_path}", + f"http://{external_host}{lm_port}{lm_path}" + ) + + @app.get("/dashboard", response_class=HTMLResponse) -async def get_dashboard(): +async def get_dashboard(request: Request): """Render the router main dashboard HTML showing system metrics, health checks, and recent token usage.""" + langfuse_url, litellm_url, llama_url = resolve_external_urls(request) + data = await get_dashboard_data() # Unpack data for the f-string template @@ -3710,7 +3804,7 @@ async def get_dashboard():

Per-model usage, token consumption & cost are tracked with full trace detail in Langfuse.

- Open Langfuse Observability → + Open Langfuse Observability →
@@ -3846,15 +3940,15 @@ async def get_dashboard():
- + {src_badge("LANGFUSE", "#e879f9")} Observability UI - + {src_badge("LITELLM", "#34d399")} Admin UI - + {src_badge("LLAMA.CPP", "#fb923c")} Server Router UI diff --git a/start-stack.sh b/start-stack.sh index 7a1a7bac..fd4f18b5 100755 --- a/start-stack.sh +++ b/start-stack.sh @@ -69,6 +69,24 @@ if [ -f "$ENV_FILE" ]; then set +a fi +# Define and export the routing domain +ROUTING_DOMAIN="${ROUTING_DOMAIN:-vendeuvre.lan}" +export ROUTING_DOMAIN + +# Derive public/local base URLs from env/config with sensible defaults, removing trailing slash +PUBLIC_BASE_URL="${PUBLIC_BASE_URL:-${BASE_URL:-${BASEURL:-https://x570.${ROUTING_DOMAIN}/llm-routing}}}" +if [[ ! "$PUBLIC_BASE_URL" =~ ^https?:// ]]; then + PUBLIC_BASE_URL="https://${PUBLIC_BASE_URL}" +fi +if [[ ! "$PUBLIC_BASE_URL" =~ /llm-routing ]]; then + PUBLIC_BASE_URL="${PUBLIC_BASE_URL%/}/llm-routing" +fi +PUBLIC_BASE_URL="${PUBLIC_BASE_URL%/}" +LOCAL_BASE_URL="${LOCAL_BASE_URL:-http://localhost:5000}" +LOCAL_BASE_URL="${LOCAL_BASE_URL%/}" +export PUBLIC_BASE_URL LOCAL_BASE_URL + + # Ensure openssl is installed if we need to generate passwords/keys if [ -z "$POSTGRES_PASSWORD" ] || [ -z "$NEXTAUTH_SECRET" ] || [ -z "$SALT" ] || [ -z "$ENCRYPTION_KEY" ] || [ -z "$LITELLM_MASTER_KEY" ] || [ -z "$ROUTER_API_KEY" ] || [ -z "$MINIO_ROOT_USER" ] || [ -z "$MINIO_ROOT_PASSWORD" ] || [ -z "$LANGFUSE_INIT_USER_PASSWORD" ] || [ -z "$REDIS_AUTH" ] || [ -z "$CLICKHOUSE_PASSWORD" ] || [ -z "$LANGFUSE_PUBLIC_KEY" ] || [ -z "$LANGFUSE_SECRET_KEY" ]; then if ! command -v openssl &>/dev/null; then @@ -511,7 +529,7 @@ if podman pod exists agent-router-pod 2>/dev/null; then fi render_pod_yaml() { - export WORKDIR HOME LITELLM_MASTER_KEY POSTGRES_PASSWORD NEXTAUTH_SECRET SALT ENCRYPTION_KEY LANGFUSE_INIT_USER_PASSWORD MINIO_ROOT_USER MINIO_ROOT_PASSWORD OLLAMA_API_KEY LANGFUSE_PUBLIC_KEY LANGFUSE_SECRET_KEY CLASSIFIER_INPUT_MAX_CHARS REDIS_AUTH CLICKHOUSE_PASSWORD + export WORKDIR HOME LITELLM_MASTER_KEY POSTGRES_PASSWORD NEXTAUTH_SECRET SALT ENCRYPTION_KEY LANGFUSE_INIT_USER_PASSWORD MINIO_ROOT_USER MINIO_ROOT_PASSWORD OLLAMA_API_KEY LANGFUSE_PUBLIC_KEY LANGFUSE_SECRET_KEY CLASSIFIER_INPUT_MAX_CHARS REDIS_AUTH CLICKHOUSE_PASSWORD PUBLIC_BASE_URL ROUTING_DOMAIN python3 - "$WORKDIR/pod.yaml" <<'PY' import os, sys, urllib.parse, json uid = os.getuid() @@ -522,9 +540,9 @@ def yaml_scalar(val): return json.dumps(val) placeholders = [ - "/home/gpav/Vrac/LAB/AI/LLM-Routing", - "/home/gpav/", - "/run/user/1000", + "WORKDIR_PLACEHOLDER", + "HOME_PLACEHOLDER", + "RUN_USER_PLACEHOLDER", "LITELLM_MASTER_KEY_PLACEHOLDER", "POSTGRES_PASSWORD_RAW_PLACEHOLDER", "POSTGRES_PASSWORD_ENCODED_PLACEHOLDER", @@ -538,15 +556,18 @@ placeholders = [ "MINIO_PASSWORD_PLACEHOLDER", "LANGFUSE_INIT_USER_PASSWORD_PLACEHOLDER", "REDIS_AUTH_PLACEHOLDER", - "CLICKHOUSE_PASSWORD_PLACEHOLDER" + "CLICKHOUSE_PASSWORD_PLACEHOLDER", + "PROXY_BASE_URL_PLACEHOLDER", + "PUBLIC_BASE_URL_PLACEHOLDER", + "ROUTING_DOMAIN_PLACEHOLDER" ] for ph in placeholders: if ph not in text: sys.stderr.write(f"Error: Required placeholder '{ph}' not found in pod.yaml. Ensure you are using the latest version of the template.\n") sys.exit(1) -text = text.replace("/home/gpav/Vrac/LAB/AI/LLM-Routing", os.environ["WORKDIR"]) -text = text.replace("/home/gpav/", os.environ["HOME"] + "/") -text = text.replace("/run/user/1000", f"/run/user/{uid}") +text = text.replace("WORKDIR_PLACEHOLDER", os.environ["WORKDIR"]) +text = text.replace("HOME_PLACEHOLDER", os.environ["HOME"]) +text = text.replace("RUN_USER_PLACEHOLDER", f"/run/user/{uid}") text = text.replace("LITELLM_MASTER_KEY_PLACEHOLDER", yaml_scalar(os.environ["LITELLM_MASTER_KEY"])) text = text.replace("POSTGRES_PASSWORD_RAW_PLACEHOLDER", yaml_scalar(os.environ["POSTGRES_PASSWORD"])) # URL-encode the postgres password for DSN insertion @@ -563,6 +584,12 @@ text = text.replace("MINIO_PASSWORD_PLACEHOLDER", yaml_scalar(os.environ["MINIO_ text = text.replace("LANGFUSE_INIT_USER_PASSWORD_PLACEHOLDER", yaml_scalar(os.environ["LANGFUSE_INIT_USER_PASSWORD"])) text = text.replace("REDIS_AUTH_PLACEHOLDER", yaml_scalar(os.environ["REDIS_AUTH"])) text = text.replace("CLICKHOUSE_PASSWORD_PLACEHOLDER", yaml_scalar(os.environ["CLICKHOUSE_PASSWORD"])) +# Derive PROXY_BASE_URL from PUBLIC_BASE_URL +public_base_url = os.environ["PUBLIC_BASE_URL"].rstrip("/") +proxy_base_url = f"{public_base_url}/litellm" +text = text.replace("PROXY_BASE_URL_PLACEHOLDER", yaml_scalar(proxy_base_url)) +text = text.replace("PUBLIC_BASE_URL_PLACEHOLDER", yaml_scalar(os.environ["PUBLIC_BASE_URL"])) +text = text.replace("ROUTING_DOMAIN_PLACEHOLDER", yaml_scalar(os.environ["ROUTING_DOMAIN"])) import re unresolved = sorted(set(re.findall(r"\b[A-Z0-9_]+_PLACEHOLDER\b", text))) if unresolved: @@ -596,13 +623,15 @@ if podman pod exists agent-router-pod 2>/dev/null; then podman pod restart agent-router-pod setup_minio_buckets verify_stack_health + echo "" echo "=========================================================================" echo "🎉 SUCCESS: LLM Triage Gateway restarted!" - echo "📍 Entry endpoint : http://localhost:5000/v1" - echo "⚙️ Dashboard URL : http://localhost:5000/dashboard" + echo "📍 Entry endpoint : ${PUBLIC_BASE_URL}/v1" + echo " (local) : ${LOCAL_BASE_URL}/v1" + echo "⚙️ Dashboard URL : ${PUBLIC_BASE_URL}/dashboard" echo "🔑 Gateway API Key : gateway-pass" - echo "🔐 LiteLLM Admin UI: http://localhost:4000/ui" + echo "🔐 LiteLLM Admin UI: ${PUBLIC_BASE_URL}/litellm/ui" echo " Username: admin | Password: $LITELLM_MASTER_KEY" echo "=========================================================================" exit 0 @@ -619,11 +648,13 @@ else verify_stack_health fi + echo "=========================================================================" echo "🎉 SUCCESS: LLM Triage Gateway successfully deployed!" -echo "📍 Entry endpoint : http://localhost:5000/v1" -echo "⚙️ Dashboard URL : http://localhost:5000/dashboard" +echo "📍 Entry endpoint : ${PUBLIC_BASE_URL}/v1" +echo " (local) : ${LOCAL_BASE_URL}/v1" +echo "⚙️ Dashboard URL : ${PUBLIC_BASE_URL}/dashboard" echo "🔑 Gateway API Key : gateway-pass" -echo "🔐 LiteLLM Admin UI: http://localhost:4000/ui" +echo "🔐 LiteLLM Admin UI: ${PUBLIC_BASE_URL}/litellm/ui" echo " Username: admin | Password: $LITELLM_MASTER_KEY" echo "========================================================================="