From e24ba199f561f71763e3491a25dfc9f7d18782b4 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Thu, 8 Oct 2026 11:05:42 -0600 Subject: [PATCH] feat: discover free OmniRoute model routes --- infra/ai-stack/README.md | 3 + infra/ai-stack/bootstrap-omniroute.sh | 285 +++++++++++++++++++++++++- 2 files changed, 287 insertions(+), 1 deletion(-) diff --git a/infra/ai-stack/README.md b/infra/ai-stack/README.md index 1fcde8e..90a4d26 100644 --- a/infra/ai-stack/README.md +++ b/infra/ai-stack/README.md @@ -27,6 +27,9 @@ Secrets: - Jeannie also generates persistent local-only OmniRoute management secrets in that env file, logs in against `127.0.0.1`, and creates provider connections through OmniRoute's management API. Secret values are never printed. +- Jeannie discovers currently free OpenRouter models and NVIDIA catalog models, + creates `agent-fast-free` and `agent-smart-free` OmniRoute combos, and writes + `/data/homelab-ai-stack/models.env` for smoke tests and local tools. - Key files and generated env files are ignored by git. The container name defaults to `omniroute` so this command owns the same gateway diff --git a/infra/ai-stack/bootstrap-omniroute.sh b/infra/ai-stack/bootstrap-omniroute.sh index 00be7a0..541115b 100644 --- a/infra/ai-stack/bootstrap-omniroute.sh +++ b/infra/ai-stack/bootstrap-omniroute.sh @@ -9,6 +9,7 @@ PORT="${LAB_OMNIROUTE_PORT:-20128}" BASE_URL="${LAB_AI_STACK_OMNIROUTE_BASE_URL:-http://127.0.0.1:${PORT}}" OPENROUTER_URL="${LAB_AI_STACK_OPENROUTER_URL:-https://openrouter.ai/api/v1}" NVIDIA_URL="${LAB_AI_STACK_NVIDIA_URL:-https://integrate.api.nvidia.com/v1}" +MODEL_ROUTES_FILE="${LAB_AI_STACK_MODEL_ROUTES_FILE:-${INSTALL_DIR}/models.env}" OMNIROUTE_BOOTSTRAP_TMP_DIR="" if [[ ! -s "${ENV_FILE}" ]]; then @@ -193,8 +194,285 @@ upsert_provider() { echo "OmniRoute provider ${provider}: configured" } +api_get() { + local cookie_jar="$1" + local auth_header="$2" + local path="$3" + local output_file="$4" + + if [[ -n "${auth_header}" ]]; then + curl -fsS -b "${cookie_jar}" -H "${auth_header}" "${BASE_URL}${path}" -o "${output_file}" + else + curl -fsS -b "${cookie_jar}" "${BASE_URL}${path}" -o "${output_file}" + fi +} + +api_post_json() { + local cookie_jar="$1" + local auth_header="$2" + local path="$3" + local payload_file="$4" + local output_file="$5" + + if [[ -n "${auth_header}" ]]; then + curl -sS -b "${cookie_jar}" -H "${auth_header}" -o "${output_file}" -w '%{http_code}' -H 'Content-Type: application/json' -X POST --data-binary @"${payload_file}" "${BASE_URL}${path}" + else + curl -sS -b "${cookie_jar}" -o "${output_file}" -w '%{http_code}' -H 'Content-Type: application/json' -X POST --data-binary @"${payload_file}" "${BASE_URL}${path}" + fi +} + +discover_model_routes() { + local openrouter_key="$1" + local nvidia_key="$2" + local output_json="$3" + + OPENROUTER_KEY="${openrouter_key}" NVIDIA_KEY="${nvidia_key}" OPENROUTER_URL="${OPENROUTER_URL}" NVIDIA_URL="${NVIDIA_URL}" python3 - "${output_json}" <<'PY' +import json +import os +import sys +import urllib.error +import urllib.request + +output_path = sys.argv[1] +openrouter_key = os.environ.get("OPENROUTER_KEY", "") +nvidia_key = os.environ.get("NVIDIA_KEY", "") +openrouter_url = os.environ["OPENROUTER_URL"].rstrip("/") +nvidia_url = os.environ["NVIDIA_URL"].rstrip("/") + + +def fetch_json(url, token=""): + headers = {"Accept": "application/json"} + if token: + headers["Authorization"] = f"Bearer {token}" + request = urllib.request.Request(url, headers=headers) + try: + with urllib.request.urlopen(request, timeout=20) as response: + return json.load(response) + except (OSError, urllib.error.HTTPError, json.JSONDecodeError): + return {} + + +def as_float(value): + try: + return float(value) + except (TypeError, ValueError): + return None + + +def priority(model): + lower = model.lower() + scores = [ + ("qwen", 0), + ("llama-3.1-8b", 1), + ("llama-3", 2), + ("mistral", 3), + ("gemma", 4), + ("deepseek", 5), + ] + for needle, score in scores: + if needle in lower: + return score + return 99 + + +openrouter_models = [] +if openrouter_key: + for item in fetch_json(f"{openrouter_url}/models", openrouter_key).get("data", []) or []: + model_id = item.get("id") + if not isinstance(model_id, str) or not model_id: + continue + pricing = item.get("pricing") or {} + prompt = as_float(pricing.get("prompt")) + completion = as_float(pricing.get("completion")) + zero_priced = prompt == 0.0 and completion == 0.0 + if model_id.endswith(":free") or zero_priced: + openrouter_models.append(f"openrouter/{model_id}") + +openrouter_models = sorted(set(openrouter_models), key=lambda value: (priority(value), value)) + +nvidia_models = [] +if nvidia_key: + for item in fetch_json(f"{nvidia_url}/models", nvidia_key).get("data", []) or []: + model_id = item.get("id") + if isinstance(model_id, str) and model_id: + nvidia_models.append(model_id if model_id.startswith("nvidia/") else f"nvidia/{model_id}") + +nvidia_models = sorted(set(nvidia_models), key=lambda value: (priority(value), value)) + +fast = (openrouter_models[:4] + nvidia_models[:2])[:6] +smart = (nvidia_models[:4] + openrouter_models[:4])[:8] + +with open(output_path, "w", encoding="utf-8") as fh: + json.dump({ + "openrouter_free": openrouter_models, + "nvidia": nvidia_models, + "agent_fast_models": fast, + "agent_smart_models": smart, + }, fh, indent=2, sort_keys=True) + fh.write("\n") +PY +} + +combo_id_for() { + local cookie_jar="$1" + local auth_header="$2" + local combo_name="$3" + local body_file="$4" + + api_get "${cookie_jar}" "${auth_header}" "/api/combos" "${body_file}" + + python3 - "${body_file}" "${combo_name}" <<'PY' +import json +import sys + +path, combo_name = sys.argv[1:3] +with open(path, encoding="utf-8") as fh: + data = json.load(fh) + +if isinstance(data, dict): + candidates = data.get("combos") or data.get("items") or data.get("data") or [] +else: + candidates = data + +for item in candidates or []: + if isinstance(item, dict) and item.get("name") == combo_name: + print(item.get("id", "")) + sys.exit(0) +sys.exit(1) +PY +} + +create_combo() { + local cookie_jar="$1" + local auth_header="$2" + local combo_name="$3" + local models_json_file="$4" + local payload_file="$5" + local body_file="$6" + local status + + python3 - "${combo_name}" "${models_json_file}" "${payload_file}" <<'PY' +import json +import sys + +combo_name, models_path, payload_path = sys.argv[1:4] +with open(models_path, encoding="utf-8") as fh: + models = json.load(fh) + +with open(payload_path, "w", encoding="utf-8") as fh: + json.dump({ + "name": combo_name, + "models": models, + "strategy": "priority", + }, fh) +PY + + status="$(api_post_json "${cookie_jar}" "${auth_header}" "/api/combos" "${payload_file}" "${body_file}")" + if [[ "${status}" != "201" && "${status}" != "200" ]]; then + echo "Failed to create OmniRoute combo ${combo_name}; HTTP ${status}." >&2 + sed -n '1,3p' "${body_file}" >&2 || true + return 1 + fi +} + +upsert_combo() { + local cookie_jar="$1" + local auth_header="$2" + local combo_name="$3" + local models_json_file="$4" + local body_file="$5" + local payload_file="$6" + local model_count + + model_count="$(python3 - "${models_json_file}" <<'PY' +import json +import sys +with open(sys.argv[1], encoding="utf-8") as fh: + print(len(json.load(fh))) +PY +)" + if [[ "${model_count}" == "0" ]]; then + echo "OmniRoute combo ${combo_name}: skipped; no eligible models discovered" + return 0 + fi + + if combo_id_for "${cookie_jar}" "${auth_header}" "${combo_name}" "${body_file}" >/dev/null 2>&1; then + echo "OmniRoute combo ${combo_name}: already configured" + return 0 + fi + + create_combo "${cookie_jar}" "${auth_header}" "${combo_name}" "${models_json_file}" "${payload_file}" "${body_file}" + echo "OmniRoute combo ${combo_name}: configured with ${model_count} free/quota model(s)" +} + +write_model_routes_file() { + local routes_json="$1" + local fast_json="$2" + local smart_json="$3" + local output_file="$4" + + python3 - "${routes_json}" "${fast_json}" "${smart_json}" "${output_file}" <<'PY' +import json +import sys + +routes_path, fast_path, smart_path, output_path = sys.argv[1:5] +with open(routes_path, encoding="utf-8") as fh: + routes = json.load(fh) +with open(fast_path, encoding="utf-8") as fh: + fast = json.load(fh) +with open(smart_path, encoding="utf-8") as fh: + smart = json.load(fh) + +fast_model = "agent-fast-free" if fast else "" +smart_model = "agent-smart-free" if smart else fast_model +direct_fast = fast[0] if fast else "" +direct_smart = smart[0] if smart else direct_fast + +with open(output_path, "w", encoding="utf-8") as fh: + fh.write("# Generated by jeannie deploy-ai-stack. Do not commit.\n") + fh.write(f"AI_STACK_AGENT_FAST_MODEL={fast_model}\n") + fh.write(f"AI_STACK_AGENT_SMART_MODEL={smart_model}\n") + fh.write(f"AI_STACK_AGENT_FAST_DIRECT_MODEL={direct_fast}\n") + fh.write(f"AI_STACK_AGENT_SMART_DIRECT_MODEL={direct_smart}\n") + fh.write(f"AI_STACK_OPENROUTER_FREE_COUNT={len(routes.get('openrouter_free') or [])}\n") + fh.write(f"AI_STACK_NVIDIA_MODEL_COUNT={len(routes.get('nvidia') or [])}\n") +PY + chmod 0600 "${output_file}" +} + +configure_free_model_routes() { + local cookie_jar="$1" + local auth_header="$2" + local openrouter_key="$3" + local nvidia_key="$4" + local routes_json="$5" + local fast_json="$6" + local smart_json="$7" + local payload_file="$8" + local body_file="$9" + + discover_model_routes "${openrouter_key}" "${nvidia_key}" "${routes_json}" + python3 - "${routes_json}" "${fast_json}" "${smart_json}" <<'PY' +import json +import sys + +routes_path, fast_path, smart_path = sys.argv[1:4] +with open(routes_path, encoding="utf-8") as fh: + routes = json.load(fh) +with open(fast_path, "w", encoding="utf-8") as fh: + json.dump(routes.get("agent_fast_models") or [], fh) +with open(smart_path, "w", encoding="utf-8") as fh: + json.dump(routes.get("agent_smart_models") or [], fh) +PY + + upsert_combo "${cookie_jar}" "${auth_header}" "agent-fast-free" "${fast_json}" "${body_file}" "${payload_file}" + upsert_combo "${cookie_jar}" "${auth_header}" "agent-smart-free" "${smart_json}" "${body_file}" "${payload_file}" + write_model_routes_file "${routes_json}" "${fast_json}" "${smart_json}" "${MODEL_ROUTES_FILE}" + echo "OmniRoute model route hints written to ${MODEL_ROUTES_FILE}" +} + main() { - local password openrouter_key nvidia_key cookie_jar headers_file body_file auth_header + local password openrouter_key nvidia_key cookie_jar headers_file body_file auth_header routes_json fast_json smart_json payload_file password="$(env_value INITIAL_PASSWORD)" openrouter_key="$(env_value OPENROUTER_API_KEY 2>/dev/null || true)" @@ -206,12 +484,17 @@ main() { cookie_jar="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/cookies.txt" headers_file="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/headers.txt" body_file="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/body.json" + routes_json="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/routes.json" + fast_json="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/fast.json" + smart_json="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/smart.json" + payload_file="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/payload.json" login_omniroute "${password}" "${cookie_jar}" "${body_file}" "${headers_file}" auth_header="$(extract_auth_header "${body_file}")" upsert_provider "${cookie_jar}" "${auth_header}" "openrouter" "openrouter-seeded" "${OPENROUTER_URL}" "${openrouter_key}" "${body_file}" upsert_provider "${cookie_jar}" "${auth_header}" "nvidia" "nvidia-seeded" "${NVIDIA_URL}" "${nvidia_key}" "${body_file}" + configure_free_model_routes "${cookie_jar}" "${auth_header}" "${openrouter_key}" "${nvidia_key}" "${routes_json}" "${fast_json}" "${smart_json}" "${payload_file}" "${body_file}" } main "$@"