fix: validate OmniRoute model routes
Homelab Main / validate (push) Waiting to run Details
Homelab Main / running-update (push) Blocked by required conditions Details
Homelab Main / debian-ops (push) Blocked by required conditions Details

This commit is contained in:
juvenal.diaz 2026-10-08 12:36:44 -06:00
parent 32562f6ac2
commit 162bee22d4
3 changed files with 188 additions and 8 deletions

View File

@ -11,6 +11,9 @@ 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:-24}"
OMNIROUTE_FAST_MODEL_TARGET="${LAB_AI_STACK_FAST_MODEL_TARGET:-4}"
OMNIROUTE_SMART_MODEL_TARGET="${LAB_AI_STACK_SMART_MODEL_TARGET:-6}"
if [[ ! -s "${ENV_FILE}" ]]; then
echo "Missing ${ENV_FILE}; run seed-secrets.sh first." >&2
@ -221,6 +224,19 @@ api_post_json() {
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"
@ -313,6 +329,135 @@ with open(output_path, "w", encoding="utf-8") as fh:
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,
"temperature": 0,
}
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"
@ -383,6 +528,8 @@ upsert_combo() {
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
@ -391,18 +538,22 @@ 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
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 combo_id_for "${cookie_jar}" "${auth_header}" "${combo_name}" "${body_file}" >/dev/null 2>&1; then
echo "OmniRoute combo ${combo_name}: already configured"
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} free/quota model(s)"
echo "OmniRoute combo ${combo_name}: configured with ${model_count} runtime-validated model(s)"
}
write_model_routes_file() {
@ -450,9 +601,35 @@ configure_free_model_routes() {
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}"
python3 - "${routes_json}" "${fast_json}" "${smart_json}" <<'PY'
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)}"
)
sys.exit(0 if fast or smart else 1)
PY
then
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
@ -467,7 +644,7 @@ 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}"
write_model_routes_file "${validated_routes_json}" "${fast_json}" "${smart_json}" "${MODEL_ROUTES_FILE}"
echo "OmniRoute model route hints written to ${MODEL_ROUTES_FILE}"
}

View File

@ -19,6 +19,7 @@ services:
OPEN_ROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
NVIDIA_API_KEY: ${NVIDIA_API_KEY:-}
NVIDIA_NIM_API_KEY: ${NVIDIA_API_KEY:-}
OMNIROUTE_API_KEY: ${OMNIROUTE_API_KEY:-sk_omniroute}
REQUIRE_API_KEY: ${REQUIRE_API_KEY:-false}
INITIAL_PASSWORD: ${INITIAL_PASSWORD:?INITIAL_PASSWORD must be seeded by seed-secrets.sh}
API_KEY_SECRET: ${API_KEY_SECRET:?API_KEY_SECRET must be seeded by seed-secrets.sh}

View File

@ -60,6 +60,7 @@ initial_password="$(existing_env_value INITIAL_PASSWORD "${ENV_FILE}" 2>/dev/nul
api_key_secret="$(existing_env_value API_KEY_SECRET "${ENV_FILE}" 2>/dev/null || random_secret)"
auth_secret="$(existing_env_value AUTH_SECRET "${ENV_FILE}" 2>/dev/null || random_secret)"
jwt_secret="$(existing_env_value JWT_SECRET "${ENV_FILE}" 2>/dev/null || random_secret)"
omniroute_api_key="$(existing_env_value OMNIROUTE_API_KEY "${ENV_FILE}" 2>/dev/null || printf 'sk_omniroute')"
tmp_file="$(mktemp)"
trap 'rm -f "${tmp_file}"' EXIT
@ -72,6 +73,7 @@ umask 077
write_kv OLLAMA_BASE_URL "${LAB_AI_STACK_OLLAMA_BASE_URL:-http://host.docker.internal:11434}"
write_kv OLLAMA_HOST "${LAB_AI_STACK_OLLAMA_HOST:-http://host.docker.internal:11434}"
write_kv REQUIRE_API_KEY "${LAB_AI_STACK_REQUIRE_API_KEY:-false}"
write_kv OMNIROUTE_API_KEY "${omniroute_api_key}"
write_kv INITIAL_PASSWORD "${initial_password}"
write_kv API_KEY_SECRET "${api_key_secret}"
write_kv AUTH_SECRET "${auth_secret}"