diff --git a/lib/jeannie/commands.sh b/lib/jeannie/commands.sh index 2dd0def..9b97481 100644 --- a/lib/jeannie/commands.sh +++ b/lib/jeannie/commands.sh @@ -1349,13 +1349,16 @@ backstage_brain_enabled() { local provider="${LAB_AI_GATEWAY_PROVIDER:-ollama}" local enabled="${LAB_BACKSTAGE_BRAIN_ENABLED:-false}" - [[ "${provider,,}" == "ollama" ]] && truthy "${enabled}" + [[ "${provider,,}" =~ ^(ollama|omniroute|openai)$ ]] && truthy "${enabled}" } backstage_brain_note() { local topic="$1" + local routes_file="${LAB_AI_STACK_MODEL_ROUTES_FILE:-/data/homelab-ai-stack/models.env}" + local provider="${LAB_AI_GATEWAY_PROVIDER:-ollama}" local endpoint="${LAB_AI_GATEWAY_URL:-${LAB_OLLAMA_URL:-http://127.0.0.1:11434}}" local model="${LAB_AI_GATEWAY_MODEL:-qwen2.5:0.5b}" + local api_key="${LAB_AI_GATEWAY_API_KEY:-${OMNIROUTE_API_KEY:-${HERMES_OMNIROUTE_API_KEY:-sk_omniroute}}}" local timeout="${LAB_AI_GATEWAY_TIMEOUT_SECONDS:-20}" local index_dir="${LAB_AI_KNOWLEDGE_INDEX_DIR:-/data/homelab-ai/index}" local context @@ -1367,6 +1370,15 @@ backstage_brain_note() { if ! command -v python3 >/dev/null 2>&1; then return 0 fi + if [[ -s "${routes_file}" ]]; then + # shellcheck disable=SC1090 + . "${routes_file}" + if [[ "${provider}" == "ollama" && -n "${AI_STACK_AGENT_FAST_MODEL:-}" ]]; then + provider="omniroute" + endpoint="${LAB_AI_GATEWAY_URL:-http://127.0.0.1:20128/v1}" + model="${LAB_AI_GATEWAY_MODEL:-${AI_STACK_AGENT_FAST_MODEL}}" + fi + fi context="$(cat)" if [[ -s "${index_dir}/index.json" ]]; then @@ -1378,14 +1390,14 @@ backstage_brain_note() { Retrieved homelab knowledge: ${retrieved_context}" fi - BACKSTAGE_CONTEXT="${context}" python3 - "${endpoint}" "${model}" "${timeout}" "${topic}" <<'PY' || true + BACKSTAGE_CONTEXT="${context}" python3 - "${provider}" "${endpoint}" "${model}" "${timeout}" "${topic}" "${api_key}" <<'PY' || true import json import os import sys import urllib.error import urllib.request -endpoint, model, timeout, topic = sys.argv[1:5] +provider, endpoint, model, timeout, topic, api_key = sys.argv[1:7] context = os.environ.get("BACKSTAGE_CONTEXT", "").strip() try: timeout_seconds = int(timeout) @@ -1404,35 +1416,47 @@ Context: payload = { "model": model, - "prompt": prompt, "stream": False, - "options": { - "temperature": 0.1, - "num_predict": 220, - }, } try: - tags_request = urllib.request.Request(f"{endpoint.rstrip('/')}/api/tags") - with urllib.request.urlopen(tags_request, timeout=3) as response: - tags = json.loads(response.read().decode("utf-8")) - available = {item.get("name", "") for item in tags.get("models", [])} - if model not in available and f"{model}:latest" not in available: - print(f"\n== Backstage Notes ==\nOllama is reachable, but model '{model}' is not pulled. Run: ollama pull {model}") - raise SystemExit(0) - - request = urllib.request.Request( - f"{endpoint.rstrip('/')}/api/generate", - data=json.dumps(payload).encode("utf-8"), - headers={"Content-Type": "application/json"}, - method="POST", - ) + if provider.lower() in ("omniroute", "openai"): + payload["messages"] = [{"role": "user", "content": prompt}] + payload["temperature"] = 0.1 + headers = {"Content-Type": "application/json"} + if api_key: + headers["Authorization"] = f"Bearer {api_key}" + request = urllib.request.Request( + f"{endpoint.rstrip('/')}/chat/completions", + data=json.dumps(payload).encode("utf-8"), + headers=headers, + method="POST", + ) + else: + tags_request = urllib.request.Request(f"{endpoint.rstrip('/')}/api/tags") + with urllib.request.urlopen(tags_request, timeout=3) as response: + tags = json.loads(response.read().decode("utf-8")) + available = {item.get("name", "") for item in tags.get("models", [])} + if model not in available and f"{model}:latest" not in available: + print(f"\n== Backstage Notes ==\nOllama is reachable, but model '{model}' is not pulled. Run: ollama pull {model}") + raise SystemExit(0) + payload["prompt"] = prompt + payload["options"] = {"temperature": 0.1, "num_predict": 220} + request = urllib.request.Request( + f"{endpoint.rstrip('/')}/api/generate", + data=json.dumps(payload).encode("utf-8"), + headers={"Content-Type": "application/json"}, + method="POST", + ) with urllib.request.urlopen(request, timeout=timeout_seconds) as response: result = json.loads(response.read().decode("utf-8")) except (OSError, TimeoutError, urllib.error.URLError, json.JSONDecodeError): raise SystemExit(0) -note = (result.get("response") or "").strip() +if provider.lower() in ("omniroute", "openai"): + note = (((result.get("choices") or [{}])[0].get("message") or {}).get("content") or "").strip() +else: + note = (result.get("response") or "").strip() if note: print("\n== Backstage Notes ==") print(note) @@ -2012,6 +2036,7 @@ doctor_cluster() { Next steps: - If API server is unreachable after a stop, run ./jeannie start-cluster. +- If the API is reachable but pods/nodes are unhealthy, run Holmes for read-only Kubernetes triage before changing workloads. - If nodes are NotReady, inspect kube-system pods and containerd/kubelet on that node. - If Pimox workers are stopped, start them with ./jeannie start-cluster. - If kubelet versions drift, run ./jeannie doctor-versions. @@ -2481,8 +2506,10 @@ ai_index() { ai_check() { local index_dir="${LAB_AI_KNOWLEDGE_INDEX_DIR:-/data/homelab-ai/index}" + local routes_file="${LAB_AI_STACK_MODEL_ROUTES_FILE:-/data/homelab-ai-stack/models.env}" local endpoint="${LAB_AI_GATEWAY_URL:-${LAB_OLLAMA_URL:-http://127.0.0.1:11434}}" local model="${LAB_AI_GATEWAY_MODEL:-qwen2.5:0.5b}" + local provider="${LAB_AI_GATEWAY_PROVIDER:-ollama}" local failures=0 require_debian_server "ai-check" @@ -2509,8 +2536,37 @@ ai_check() { failures=$((failures + 1)) fi + if command -v holmes >/dev/null 2>&1; then + printf '%-28s ok - %s\n' "holmes k8s triage" "$(command -v holmes)" + else + printf '%-28s missing - install holmes for Kubernetes triage\n' "holmes k8s triage" + fi + + if [[ -s "${routes_file}" ]]; then + # shellcheck disable=SC1090 + . "${routes_file}" + printf '%-28s ok - %s\n' "ai stack routes" "${routes_file}" + printf '%-28s %s\n' "agent fast model" "${AI_STACK_AGENT_FAST_MODEL:-unset}" + printf '%-28s %s\n' "agent smart model" "${AI_STACK_AGENT_SMART_MODEL:-unset}" + if [[ "${provider}" == "ollama" && -n "${AI_STACK_AGENT_FAST_MODEL:-}" ]]; then + provider="omniroute" + endpoint="${LAB_AI_GATEWAY_URL:-http://127.0.0.1:20128/v1}" + model="${LAB_AI_GATEWAY_MODEL:-${AI_STACK_AGENT_FAST_MODEL}}" + fi + else + printf '%-28s missing - run ./jeannie deploy-ai-stack\n' "ai stack routes" + fi + if backstage_brain_enabled; then - if curl -fsS --max-time 5 "${endpoint%/}/api/tags" >/dev/null 2>&1; then + if [[ "${provider,,}" == "omniroute" || "${provider,,}" == "openai" ]]; then + if curl -sS -o /dev/null -w '%{http_code}' --max-time 5 "${endpoint%/}/models" 2>/dev/null | grep -Eq '^(200|401)$'; then + printf '%-28s ok - %s\n' "omniroute endpoint" "${endpoint}" + printf '%-28s ok - %s\n' "omniroute model" "${model}" + else + printf '%-28s unreachable - %s\n' "omniroute endpoint" "${endpoint}" + failures=$((failures + 1)) + fi + elif curl -fsS --max-time 5 "${endpoint%/}/api/tags" >/dev/null 2>&1; then printf '%-28s ok - %s\n' "ollama endpoint" "${endpoint}" if python3 - "${endpoint}" "${model}" <<'PY' import json diff --git a/scripts/report-ui b/scripts/report-ui index e43d56d..48f3d34 100644 --- a/scripts/report-ui +++ b/scripts/report-ui @@ -14,7 +14,7 @@ Report UI flags: --all Show ok, skip, warning, and failing items. --details Show the compact report plus detail fields. --json Print structured JSON. - --no-local-rca Do not ask local Ollama for the focused RCA summary. + --no-local-rca Do not ask the local AI gateway for the focused RCA summary. --verbose Use the older full diagnostic output when supported. EOF } @@ -168,15 +168,21 @@ report_ui_render() { report_ui_local_rca() { local title="$1" + local routes_file="${LAB_AI_STACK_MODEL_ROUTES_FILE:-/data/homelab-ai-stack/models.env}" + local provider="${LAB_DOCTOR_RCA_PROVIDER:-${LAB_AI_GATEWAY_PROVIDER:-}}" local ollama_url="${LAB_OLLAMA_URL:-http://127.0.0.1:11434}" - local model="${LAB_DOCTOR_LOCAL_MODEL:-${LAB_OLLAMA_MODEL:-llama3.2:3b}}" + local omniroute_url="${LAB_AI_GATEWAY_URL:-http://127.0.0.1:20128/v1}" + local omniroute_key="${LAB_AI_GATEWAY_API_KEY:-${OMNIROUTE_API_KEY:-${HERMES_OMNIROUTE_API_KEY:-sk_omniroute}}}" + local model local problems local prompt local payload local response local answer + local error_message local tags_response local curl_status + local http_status problems="$(awk -F'\t' ' ($1 == "fail" || $1 == "warn") { @@ -189,21 +195,23 @@ report_ui_local_rca() { return 0 fi - printf '\n== Local Model RCA ==\n' - if ! command -v curl >/dev/null 2>&1 || ! command -v jq >/dev/null 2>&1; then - printf 'skipped: curl and jq are required to ask Ollama for local RCA.\n' - printf 'fix: install curl jq, or rerun with --no-local-rca.\n' - return 0 + if [[ -s "${routes_file}" ]]; then + # shellcheck disable=SC1090 + . "${routes_file}" fi + if [[ -z "${provider}" ]]; then + if [[ -n "${AI_STACK_AGENT_SMART_MODEL:-}" ]]; then + provider="omniroute" + else + provider="ollama" + fi + fi + model="${LAB_DOCTOR_LOCAL_MODEL:-${LAB_AI_GATEWAY_MODEL:-${AI_STACK_AGENT_SMART_MODEL:-${LAB_OLLAMA_MODEL:-llama3.2:3b}}}}" - tags_response="$(curl -fsS --connect-timeout 2 --max-time 5 "${ollama_url%/}/api/tags" 2>/dev/null || true)" - if [[ -z "${tags_response}" ]]; then - printf 'skipped: Ollama is not reachable at %s; deterministic focus above is still valid.\n' "${ollama_url%/}" - return 0 - fi - if ! printf '%s' "${tags_response}" | jq -e --arg model "${model}" '.models[]?.name == $model' >/dev/null 2>&1; then - printf 'skipped: model %s is not installed in Ollama; deterministic focus above is still valid.\n' "${model}" - printf 'hint: set LAB_DOCTOR_LOCAL_MODEL to one from `ollama list`, or pull %s.\n' "${model}" + printf '\n== AI RCA ==\n' + if ! command -v curl >/dev/null 2>&1 || ! command -v jq >/dev/null 2>&1; then + printf 'skipped: curl and jq are required to ask the AI gateway for RCA.\n' + printf 'fix: install curl jq, or rerun with --no-local-rca.\n' return 0 fi @@ -215,7 +223,8 @@ Task: 1. Pick the single highest-impact issue to focus first. 2. Give likely root cause, evidence, immediate mitigation, and long-term redesign. 3. Return exactly four bullets: Focus, Root cause, Mitigation, Redesign. -4. Keep it concise and practical. Do not invent commands not implied by the fix field. +4. For Kubernetes pod/node issues, prefer read-only Holmes triage before mutation. +5. Keep it concise and practical. Do not invent commands not implied by the fix field. Report title: ${title} Problems: @@ -223,27 +232,73 @@ ${problems} EOF )" - payload="$(jq -n \ - --arg model "${model}" \ - --arg prompt "${prompt}" \ - '{model: $model, prompt: $prompt, stream: false, options: {temperature: 0.1}}')" - set +e - response="$(curl -fsS --connect-timeout 2 --max-time "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}" \ - -H 'Content-Type: application/json' \ - -d "${payload}" \ - "${ollama_url%/}/api/generate" 2>/dev/null)" - curl_status=$? - set -e - answer="$(printf '%s' "${response}" | jq -r '.response // empty' 2>/dev/null || true)" - if [[ -z "${answer}" ]]; then - if [[ "${curl_status}" -eq 28 ]]; then - printf 'skipped: model %s timed out after %ss; deterministic focus above is still valid.\n' "${model}" "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}" - printf 'hint: use LAB_DOCTOR_LOCAL_MODEL=qwen2.5:0.5b or increase LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS.\n' - else - printf 'skipped: Ollama returned no RCA using model %s; deterministic focus above is still valid.\n' "${model}" - fi - return 0 - fi + case "${provider,,}" in + omniroute | openai) + http_status="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 2 --max-time 5 "${omniroute_url%/}/models" 2>/dev/null || true)" + if [[ "${http_status}" != "200" && "${http_status}" != "401" ]]; then + printf 'skipped: OmniRoute is not reachable at %s; deterministic focus above is still valid.\n' "${omniroute_url%/}" + return 0 + fi + payload="$(jq -n \ + --arg model "${model}" \ + --arg prompt "${prompt}" \ + '{model: $model, messages: [{role: "user", content: $prompt}], stream: false, temperature: 0.1}')" + set +e + response="$(curl -sS --connect-timeout 2 --max-time "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}" \ + -H "Authorization: Bearer ${omniroute_key}" \ + -H 'Content-Type: application/json' \ + -d "${payload}" \ + "${omniroute_url%/}/chat/completions" 2>/dev/null)" + curl_status=$? + set -e + answer="$(printf '%s' "${response}" | jq -r '.choices[0].message.content // empty' 2>/dev/null || true)" + error_message="$(printf '%s' "${response}" | jq -r '.error.message // empty' 2>/dev/null || true)" + if [[ -z "${answer}" ]]; then + if [[ "${curl_status}" -eq 28 ]]; then + printf 'skipped: OmniRoute model %s timed out after %ss; deterministic focus above is still valid.\n' "${model}" "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}" + elif [[ -n "${error_message}" ]]; then + printf 'skipped: OmniRoute returned no RCA using model %s: %s\n' "${model}" "${error_message}" + else + printf 'skipped: OmniRoute returned no RCA using model %s; deterministic focus above is still valid.\n' "${model}" + fi + return 0 + fi + ;; + *) + tags_response="$(curl -fsS --connect-timeout 2 --max-time 5 "${ollama_url%/}/api/tags" 2>/dev/null || true)" + if [[ -z "${tags_response}" ]]; then + printf 'skipped: Ollama is not reachable at %s; deterministic focus above is still valid.\n' "${ollama_url%/}" + return 0 + fi + if ! printf '%s' "${tags_response}" | jq -e --arg model "${model}" '.models[]?.name == $model' >/dev/null 2>&1; then + printf 'skipped: model %s is not installed in Ollama; deterministic focus above is still valid.\n' "${model}" + printf 'hint: set LAB_DOCTOR_LOCAL_MODEL to one from `ollama list`, or pull %s.\n' "${model}" + return 0 + fi + + payload="$(jq -n \ + --arg model "${model}" \ + --arg prompt "${prompt}" \ + '{model: $model, prompt: $prompt, stream: false, options: {temperature: 0.1}}')" + set +e + response="$(curl -fsS --connect-timeout 2 --max-time "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}" \ + -H 'Content-Type: application/json' \ + -d "${payload}" \ + "${ollama_url%/}/api/generate" 2>/dev/null)" + curl_status=$? + set -e + answer="$(printf '%s' "${response}" | jq -r '.response // empty' 2>/dev/null || true)" + if [[ -z "${answer}" ]]; then + if [[ "${curl_status}" -eq 28 ]]; then + printf 'skipped: model %s timed out after %ss; deterministic focus above is still valid.\n' "${model}" "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}" + printf 'hint: use LAB_DOCTOR_LOCAL_MODEL=qwen2.5:0.5b or increase LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS.\n' + else + printf 'skipped: Ollama returned no RCA using model %s; deterministic focus above is still valid.\n' "${model}" + fi + return 0 + fi + ;; + esac printf '%s\n' "${answer}" }