793 lines
26 KiB
Bash
793 lines
26 KiB
Bash
#!/usr/bin/env bash
|
|
# Bootstrap OmniRoute management auth and provider connections.
|
|
# This script intentionally never prints secret values.
|
|
set -euo pipefail
|
|
|
|
INSTALL_DIR="${LAB_AI_STACK_INSTALL_DIR:-/data/homelab-ai-stack}"
|
|
ENV_FILE="${LAB_AI_STACK_ENV_FILE:-${INSTALL_DIR}/.env}"
|
|
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=""
|
|
OMNIROUTE_MODEL_VALIDATE_ATTEMPTS="${LAB_AI_STACK_MODEL_VALIDATE_ATTEMPTS:-4}"
|
|
OMNIROUTE_FAST_MODEL_TARGET="${LAB_AI_STACK_FAST_MODEL_TARGET:-1}"
|
|
OMNIROUTE_SMART_MODEL_TARGET="${LAB_AI_STACK_SMART_MODEL_TARGET:-2}"
|
|
DEFAULT_OPENROUTER_MODELS="openrouter/apodex/apodex-1.1-mini:free,openrouter/cohere/north-mini-code:free,openrouter/google/gemma-4-26b-a4b-it:free,openrouter/google/gemma-4-31b-it:free"
|
|
if [[ ${LAB_AI_STACK_OPENROUTER_MODELS+x} ]]; then
|
|
OMNIROUTE_OPENROUTER_MODELS="${LAB_AI_STACK_OPENROUTER_MODELS}"
|
|
else
|
|
OMNIROUTE_OPENROUTER_MODELS="${DEFAULT_OPENROUTER_MODELS}"
|
|
fi
|
|
if [[ ${LAB_AI_STACK_NVIDIA_MODELS+x} ]]; then
|
|
OMNIROUTE_NVIDIA_MODELS="${LAB_AI_STACK_NVIDIA_MODELS}"
|
|
else
|
|
OMNIROUTE_NVIDIA_MODELS=""
|
|
fi
|
|
OMNIROUTE_ENABLE_NVIDIA_DISCOVERY="${LAB_AI_STACK_ENABLE_NVIDIA_DISCOVERY:-false}"
|
|
|
|
if [[ ! -s "${ENV_FILE}" ]]; then
|
|
echo "Missing ${ENV_FILE}; run seed-secrets.sh first." >&2
|
|
exit 1
|
|
fi
|
|
|
|
env_value() {
|
|
local key="$1"
|
|
awk -F= -v key="${key}" '$1 == key { sub(/^[^=]*=/, ""); print; found = 1 } END { exit found ? 0 : 1 }' "${ENV_FILE}"
|
|
}
|
|
|
|
cleanup() {
|
|
if [[ -n "${OMNIROUTE_BOOTSTRAP_TMP_DIR}" && -d "${OMNIROUTE_BOOTSTRAP_TMP_DIR}" ]]; then
|
|
rm -rf "${OMNIROUTE_BOOTSTRAP_TMP_DIR}"
|
|
fi
|
|
}
|
|
|
|
trap cleanup EXIT
|
|
|
|
wait_for_omniroute() {
|
|
local status
|
|
|
|
for _ in $(seq 1 30); do
|
|
status="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 2 --max-time 5 "${BASE_URL}/api/auth/status" 2>/dev/null || true)"
|
|
case "${status}" in
|
|
200 | 401 | 403)
|
|
return 0
|
|
;;
|
|
esac
|
|
sleep 2
|
|
done
|
|
|
|
echo "OmniRoute did not become reachable at ${BASE_URL}." >&2
|
|
exit 1
|
|
}
|
|
|
|
login_omniroute() {
|
|
local password="$1"
|
|
local cookie_jar="$2"
|
|
local body_file="$3"
|
|
local headers_file="$4"
|
|
local status
|
|
|
|
status="$(
|
|
PASSWORD="${password}" python3 - <<'PY' |
|
|
import json
|
|
import os
|
|
|
|
print(json.dumps({"password": os.environ["PASSWORD"]}))
|
|
PY
|
|
curl -sS \
|
|
-D "${headers_file}" \
|
|
-c "${cookie_jar}" \
|
|
-o "${body_file}" \
|
|
-w '%{http_code}' \
|
|
-H 'Content-Type: application/json' \
|
|
-X POST \
|
|
--data-binary @- \
|
|
"${BASE_URL}/api/auth/login"
|
|
)"
|
|
|
|
if [[ "${status}" != "200" ]]; then
|
|
echo "OmniRoute management login failed with HTTP ${status}." >&2
|
|
sed -n '1,3p' "${body_file}" >&2 || true
|
|
exit 1
|
|
fi
|
|
}
|
|
|
|
extract_auth_header() {
|
|
local body_file="$1"
|
|
local token
|
|
|
|
token="$(
|
|
python3 - "${body_file}" <<'PY' 2>/dev/null || true
|
|
import json
|
|
import sys
|
|
|
|
with open(sys.argv[1], encoding="utf-8") as fh:
|
|
data = json.load(fh)
|
|
|
|
for key in ("token", "accessToken", "jwt", "authToken"):
|
|
value = data.get(key)
|
|
if isinstance(value, str) and value:
|
|
print(value)
|
|
break
|
|
PY
|
|
)"
|
|
|
|
if [[ -n "${token}" ]]; then
|
|
printf 'Authorization: Bearer %s\n' "${token}"
|
|
fi
|
|
}
|
|
|
|
provider_id_for() {
|
|
local cookie_jar="$1"
|
|
local auth_header="$2"
|
|
local provider="$3"
|
|
local name="$4"
|
|
local body_file="$5"
|
|
|
|
if [[ -n "${auth_header}" ]]; then
|
|
curl -fsS -b "${cookie_jar}" -H "${auth_header}" "${BASE_URL}/api/providers" -o "${body_file}"
|
|
else
|
|
curl -fsS -b "${cookie_jar}" "${BASE_URL}/api/providers" -o "${body_file}"
|
|
fi
|
|
|
|
python3 - "${body_file}" "${provider}" "${name}" <<'PY'
|
|
import json
|
|
import sys
|
|
|
|
path, provider, name = sys.argv[1:4]
|
|
with open(path, encoding="utf-8") as fh:
|
|
data = json.load(fh)
|
|
|
|
for item in data.get("connections", []) or []:
|
|
if item.get("provider") == provider and item.get("name") == name:
|
|
print(item.get("id", ""))
|
|
sys.exit(0)
|
|
sys.exit(1)
|
|
PY
|
|
}
|
|
|
|
create_provider() {
|
|
local cookie_jar="$1"
|
|
local auth_header="$2"
|
|
local provider="$3"
|
|
local name="$4"
|
|
local url="$5"
|
|
local api_key="$6"
|
|
local body_file="$7"
|
|
local status
|
|
|
|
status="$(
|
|
PROVIDER="${provider}" NAME="${name}" URL="${url}" API_KEY="${api_key}" python3 - <<'PY' |
|
|
import json
|
|
import os
|
|
|
|
print(json.dumps({
|
|
"provider": os.environ["PROVIDER"],
|
|
"name": os.environ["NAME"],
|
|
"url": os.environ["URL"],
|
|
"apiKey": os.environ["API_KEY"],
|
|
"isActive": True,
|
|
"maxConcurrent": 2,
|
|
}))
|
|
PY
|
|
if [[ -n "${auth_header}" ]]; then
|
|
curl -sS -b "${cookie_jar}" -H "${auth_header}" -o "${body_file}" -w '%{http_code}' -H 'Content-Type: application/json' -X POST --data-binary @- "${BASE_URL}/api/providers"
|
|
else
|
|
curl -sS -b "${cookie_jar}" -o "${body_file}" -w '%{http_code}' -H 'Content-Type: application/json' -X POST --data-binary @- "${BASE_URL}/api/providers"
|
|
fi
|
|
)"
|
|
|
|
if [[ "${status}" != "201" && "${status}" != "200" ]]; then
|
|
echo "Failed to create OmniRoute provider ${provider} (${name}); HTTP ${status}." >&2
|
|
sed -n '1,3p' "${body_file}" >&2 || true
|
|
exit 1
|
|
fi
|
|
}
|
|
|
|
upsert_provider() {
|
|
local cookie_jar="$1"
|
|
local auth_header="$2"
|
|
local provider="$3"
|
|
local name="$4"
|
|
local url="$5"
|
|
local api_key="$6"
|
|
local body_file="$7"
|
|
|
|
if [[ -z "${api_key}" ]]; then
|
|
echo "OmniRoute provider ${provider}: skipped; key missing"
|
|
return 0
|
|
fi
|
|
|
|
if provider_id_for "${cookie_jar}" "${auth_header}" "${provider}" "${name}" "${body_file}" >/dev/null 2>&1; then
|
|
echo "OmniRoute provider ${provider}: already configured"
|
|
return 0
|
|
fi
|
|
|
|
create_provider "${cookie_jar}" "${auth_header}" "${provider}" "${name}" "${url}" "${api_key}" "${body_file}"
|
|
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
|
|
}
|
|
|
|
api_delete() {
|
|
local cookie_jar="$1"
|
|
local auth_header="$2"
|
|
local path="$3"
|
|
local output_file="$4"
|
|
|
|
if [[ -n "${auth_header}" ]]; then
|
|
curl -sS -b "${cookie_jar}" -H "${auth_header}" -o "${output_file}" -w '%{http_code}' -X DELETE "${BASE_URL}${path}"
|
|
else
|
|
curl -sS -b "${cookie_jar}" -o "${output_file}" -w '%{http_code}' -X DELETE "${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}" \
|
|
OPENROUTER_MODELS="${OMNIROUTE_OPENROUTER_MODELS}" \
|
|
NVIDIA_MODELS="${OMNIROUTE_NVIDIA_MODELS}" \
|
|
ENABLE_NVIDIA_DISCOVERY="${OMNIROUTE_ENABLE_NVIDIA_DISCOVERY}" \
|
|
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("/")
|
|
preferred_openrouter = os.environ.get("OPENROUTER_MODELS", "")
|
|
preferred_nvidia = os.environ.get("NVIDIA_MODELS", "")
|
|
enable_nvidia_discovery = os.environ.get("ENABLE_NVIDIA_DISCOVERY", "").lower() in ("1", "true", "yes", "on")
|
|
|
|
|
|
def csv_models(value):
|
|
return [item.strip() for item in value.split(",") if item.strip()]
|
|
|
|
|
|
def unique(values):
|
|
seen = set()
|
|
result = []
|
|
for value in values:
|
|
if value and value not in seen:
|
|
seen.add(value)
|
|
result.append(value)
|
|
return result
|
|
|
|
|
|
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 = [
|
|
("apodex", 0),
|
|
("north-mini-code", 1),
|
|
("gemma-4", 2),
|
|
("gemma", 3),
|
|
("llama-3.1-8b", 4),
|
|
("llama-3", 5),
|
|
("mistral", 6),
|
|
("deepseek", 7),
|
|
("qwen", 90),
|
|
]
|
|
for needle, score in scores:
|
|
if needle in lower:
|
|
return score
|
|
return 99
|
|
|
|
|
|
openrouter_models = []
|
|
openrouter_discovered = []
|
|
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_discovered.append(f"openrouter/{model_id}")
|
|
|
|
preferred_openrouter_models = csv_models(preferred_openrouter)
|
|
openrouter_models = unique(
|
|
preferred_openrouter_models
|
|
+ sorted(set(openrouter_discovered), key=lambda value: (priority(value), value))
|
|
)
|
|
|
|
nvidia_discovered = []
|
|
if nvidia_key and enable_nvidia_discovery:
|
|
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_discovered.append(model_id if model_id.startswith("nvidia/") else f"nvidia/{model_id}")
|
|
|
|
nvidia_models = unique(
|
|
csv_models(preferred_nvidia)
|
|
+ sorted(set(nvidia_discovered), key=lambda value: (priority(value), value))
|
|
)
|
|
|
|
fast = openrouter_models[:4] + nvidia_models[:1]
|
|
smart = openrouter_models[:4] + nvidia_models[:2]
|
|
|
|
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
|
|
}
|
|
|
|
validate_model_routes() {
|
|
local routes_json="$1"
|
|
local api_key="$2"
|
|
local output_json="$3"
|
|
|
|
BASE_URL="${BASE_URL}" \
|
|
OMNIROUTE_API_KEY="${api_key}" \
|
|
VALIDATE_ATTEMPTS="${OMNIROUTE_MODEL_VALIDATE_ATTEMPTS}" \
|
|
FAST_TARGET="${OMNIROUTE_FAST_MODEL_TARGET}" \
|
|
SMART_TARGET="${OMNIROUTE_SMART_MODEL_TARGET}" \
|
|
python3 - "${routes_json}" "${output_json}" <<'PY'
|
|
import json
|
|
import os
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
routes_path, output_path = sys.argv[1:3]
|
|
base_url = os.environ["BASE_URL"].rstrip("/")
|
|
api_key = os.environ.get("OMNIROUTE_API_KEY", "")
|
|
attempt_limit = int(os.environ.get("VALIDATE_ATTEMPTS", "24"))
|
|
fast_target = int(os.environ.get("FAST_TARGET", "4"))
|
|
smart_target = int(os.environ.get("SMART_TARGET", "6"))
|
|
|
|
with open(routes_path, encoding="utf-8") as fh:
|
|
routes = json.load(fh)
|
|
|
|
openrouter = routes.get("openrouter_free") or []
|
|
nvidia = routes.get("nvidia") or []
|
|
|
|
|
|
def unique(values):
|
|
seen = set()
|
|
result = []
|
|
for value in values:
|
|
if value and value not in seen:
|
|
seen.add(value)
|
|
result.append(value)
|
|
return result
|
|
|
|
|
|
def validate(model):
|
|
headers = {
|
|
"Content-Type": "application/json",
|
|
"Accept": "application/json",
|
|
}
|
|
if api_key:
|
|
headers["Authorization"] = f"Bearer {api_key}"
|
|
payload = {
|
|
"model": model,
|
|
"messages": [{"role": "user", "content": "Return only: ok"}],
|
|
"stream": False,
|
|
"max_tokens": 8,
|
|
}
|
|
request = urllib.request.Request(
|
|
f"{base_url}/v1/chat/completions",
|
|
data=json.dumps(payload).encode("utf-8"),
|
|
headers=headers,
|
|
method="POST",
|
|
)
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=45) as response:
|
|
data = json.load(response)
|
|
except urllib.error.HTTPError as exc:
|
|
try:
|
|
body = exc.read(4096).decode("utf-8", errors="replace")
|
|
except Exception:
|
|
body = ""
|
|
return False, f"http_{exc.code}:{body[:240]}"
|
|
except Exception as exc:
|
|
return False, f"{type(exc).__name__}:{str(exc)[:240]}"
|
|
|
|
choices = data.get("choices") or []
|
|
if choices:
|
|
message = choices[0].get("message") or {}
|
|
content = message.get("content")
|
|
if isinstance(content, str) and content.strip():
|
|
return True, "ok"
|
|
return False, f"empty_response:{json.dumps(data)[:240]}"
|
|
|
|
|
|
def collect(candidates, target):
|
|
valid = []
|
|
failures = []
|
|
for model in unique(candidates):
|
|
if len(valid) >= target:
|
|
break
|
|
if len(valid) + len(failures) >= attempt_limit:
|
|
break
|
|
ok, reason = validate(model)
|
|
if ok:
|
|
valid.append(model)
|
|
else:
|
|
failures.append({"model": model, "reason": reason})
|
|
return valid, failures
|
|
|
|
|
|
# Prefer OpenRouter for both routes because the NVIDIA catalog has included
|
|
# slugs that list successfully but fail at chat-completion time through the
|
|
# gateway. NVIDIA remains in the candidate pool and is admitted only if the
|
|
# runtime validation call succeeds.
|
|
fast_candidates = unique(openrouter + nvidia)
|
|
smart_candidates = unique(openrouter + nvidia)
|
|
fast, fast_failures = collect(fast_candidates, fast_target)
|
|
smart, smart_failures = collect(smart_candidates, smart_target)
|
|
|
|
with open(output_path, "w", encoding="utf-8") as fh:
|
|
json.dump(
|
|
{
|
|
**routes,
|
|
"agent_fast_models": fast,
|
|
"agent_smart_models": smart or fast,
|
|
"validation": {
|
|
"attempt_limit": attempt_limit,
|
|
"fast_failures": fast_failures[:12],
|
|
"smart_failures": smart_failures[:12],
|
|
"fast_valid_count": len(fast),
|
|
"smart_valid_count": len(smart or fast),
|
|
},
|
|
},
|
|
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
|
|
local existing_id
|
|
local delete_status
|
|
|
|
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 existing_id="$(combo_id_for "${cookie_jar}" "${auth_header}" "${combo_name}" "${body_file}" 2>/dev/null)" && [[ -n "${existing_id}" ]]; then
|
|
delete_status="$(api_delete "${cookie_jar}" "${auth_header}" "/api/combos/${existing_id}" "${body_file}")"
|
|
if [[ "${delete_status}" != "200" && "${delete_status}" != "204" && "${delete_status}" != "404" ]]; then
|
|
echo "Failed to refresh existing OmniRoute combo ${combo_name}; DELETE HTTP ${delete_status}." >&2
|
|
sed -n '1,3p' "${body_file}" >&2 || true
|
|
return 1
|
|
fi
|
|
fi
|
|
|
|
if [[ "${model_count}" == "0" ]]; then
|
|
echo "OmniRoute combo ${combo_name}: removed stale combo; no runtime-validated models available"
|
|
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} runtime-validated model(s)"
|
|
}
|
|
|
|
remove_combo_if_exists() {
|
|
local cookie_jar="$1"
|
|
local auth_header="$2"
|
|
local combo_name="$3"
|
|
local body_file="$4"
|
|
local existing_id
|
|
local delete_status
|
|
|
|
if existing_id="$(combo_id_for "${cookie_jar}" "${auth_header}" "${combo_name}" "${body_file}" 2>/dev/null)" && [[ -n "${existing_id}" ]]; then
|
|
delete_status="$(api_delete "${cookie_jar}" "${auth_header}" "/api/combos/${existing_id}" "${body_file}")"
|
|
if [[ "${delete_status}" != "200" && "${delete_status}" != "204" && "${delete_status}" != "404" ]]; then
|
|
echo "Failed to remove stale OmniRoute combo ${combo_name}; DELETE HTTP ${delete_status}." >&2
|
|
sed -n '1,3p' "${body_file}" >&2 || true
|
|
return 1
|
|
fi
|
|
echo "OmniRoute combo ${combo_name}: removed stale combo"
|
|
fi
|
|
}
|
|
|
|
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("AI_STACK_MODEL_VALIDATION_STATUS=ok\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")
|
|
validation = routes.get("validation") or {}
|
|
fh.write(f"AI_STACK_VALIDATED_FAST_COUNT={validation.get('fast_valid_count', len(fast))}\n")
|
|
fh.write(f"AI_STACK_VALIDATED_SMART_COUNT={validation.get('smart_valid_count', len(smart))}\n")
|
|
PY
|
|
chmod 0600 "${output_file}"
|
|
}
|
|
|
|
write_invalid_model_routes_file() {
|
|
local routes_json="$1"
|
|
local output_file="$2"
|
|
|
|
python3 - "${routes_json}" "${output_file}" <<'PY'
|
|
import json
|
|
import sys
|
|
|
|
routes_path, output_path = sys.argv[1:3]
|
|
try:
|
|
with open(routes_path, encoding="utf-8") as fh:
|
|
routes = json.load(fh)
|
|
except Exception:
|
|
routes = {}
|
|
|
|
validation = routes.get("validation") or {}
|
|
with open(output_path, "w", encoding="utf-8") as fh:
|
|
fh.write("# Generated by jeannie deploy-ai-stack. Do not commit.\n")
|
|
fh.write("AI_STACK_AGENT_FAST_MODEL=\n")
|
|
fh.write("AI_STACK_AGENT_SMART_MODEL=\n")
|
|
fh.write("AI_STACK_AGENT_FAST_DIRECT_MODEL=\n")
|
|
fh.write("AI_STACK_AGENT_SMART_DIRECT_MODEL=\n")
|
|
fh.write("AI_STACK_MODEL_VALIDATION_STATUS=failed\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")
|
|
fh.write(f"AI_STACK_VALIDATED_FAST_COUNT={validation.get('fast_valid_count', 0)}\n")
|
|
fh.write(f"AI_STACK_VALIDATED_SMART_COUNT={validation.get('smart_valid_count', 0)}\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"
|
|
local validated_routes_json="${routes_json}.validated"
|
|
local omniroute_api_key
|
|
|
|
discover_model_routes "${openrouter_key}" "${nvidia_key}" "${routes_json}"
|
|
omniroute_api_key="$(env_value OMNIROUTE_API_KEY 2>/dev/null || printf 'sk_omniroute')"
|
|
validate_model_routes "${routes_json}" "${omniroute_api_key}" "${validated_routes_json}"
|
|
if ! python3 - "${validated_routes_json}" <<'PY'
|
|
import json
|
|
import sys
|
|
with open(sys.argv[1], encoding="utf-8") as fh:
|
|
data = json.load(fh)
|
|
validation = data.get("validation") or {}
|
|
fast = int(validation.get("fast_valid_count", 0) or 0)
|
|
smart = int(validation.get("smart_valid_count", 0) or 0)
|
|
print(
|
|
"OmniRoute runtime model validation: "
|
|
f"fast={fast} "
|
|
f"smart={smart} "
|
|
f"attempt_limit={validation.get('attempt_limit', 0)}"
|
|
)
|
|
for route_name, failures in (
|
|
("fast", validation.get("fast_failures") or []),
|
|
("smart", validation.get("smart_failures") or []),
|
|
):
|
|
if failures:
|
|
first = failures[0]
|
|
print(
|
|
"OmniRoute first failed "
|
|
f"{route_name} candidate: "
|
|
f"{first.get('model', 'unknown')} -> "
|
|
f"{first.get('reason', 'unknown')}"
|
|
)
|
|
sys.exit(0 if fast or smart else 1)
|
|
PY
|
|
then
|
|
remove_combo_if_exists "${cookie_jar}" "${auth_header}" "agent-fast-free" "${body_file}"
|
|
remove_combo_if_exists "${cookie_jar}" "${auth_header}" "agent-smart-free" "${body_file}"
|
|
write_invalid_model_routes_file "${validated_routes_json}" "${MODEL_ROUTES_FILE}"
|
|
echo "No OmniRoute models passed runtime validation; refusing to keep or create stale AI routes." >&2
|
|
echo "Check provider quota/cooldown or seed a known-good provider key, then rerun ./jeannie deploy-ai-stack." >&2
|
|
return 1
|
|
fi
|
|
|
|
python3 - "${validated_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 "${validated_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 routes_json fast_json smart_json payload_file
|
|
|
|
password="$(env_value INITIAL_PASSWORD)"
|
|
openrouter_key="$(env_value OPENROUTER_API_KEY 2>/dev/null || true)"
|
|
nvidia_key="$(env_value NVIDIA_API_KEY 2>/dev/null || true)"
|
|
|
|
wait_for_omniroute
|
|
|
|
OMNIROUTE_BOOTSTRAP_TMP_DIR="$(mktemp -d)"
|
|
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 "$@"
|