diff --git a/Makefile-quickstart b/Makefile-quickstart index 4427a55be..3a1e6b31e 100644 --- a/Makefile-quickstart +++ b/Makefile-quickstart @@ -17,6 +17,8 @@ PROVIDER ?= MODEL ?= API_KEY ?= ENDPOINT_URL ?= +# Comma-separated SAW-BOM profiles for openshell-saw-create (default: data-science) +PROFILES ?= WEB_SEARCH ?= GCP_SA_JSON ?= OIDC_ISSUER ?= @@ -369,7 +371,7 @@ openshell-saw-create: .check-saw-name ## Provision a sandbox (PROVIDER=, MODEL=, OPENSHELL_SAW_NAME=$(OPENSHELL_SAW_NAME) SAW_CHART=$(SAW_CHART) \ SANDBOX_IMAGE=$(SANDBOX_IMAGE) AGENT=$(AGENT) \ PROVIDER=$(PROVIDER) MODEL=$(MODEL) API_KEY=$(API_KEY) \ - ENDPOINT_URL=$(ENDPOINT_URL) WEB_SEARCH=$(WEB_SEARCH) GCP_SA_JSON=$(GCP_SA_JSON) \ + ENDPOINT_URL=$(ENDPOINT_URL) PROFILES=$(PROFILES) WEB_SEARCH=$(WEB_SEARCH) GCP_SA_JSON=$(GCP_SA_JSON) \ OIDC_ISSUER=$(OIDC_ISSUER) OIDC_CLIENT_ID=$(OIDC_CLIENT_ID) \ OIDC_TOKEN_DIR=$(OIDC_TOKEN_DIR) OWNER=$(OWNER) \ SCRIPTS_DIR=$(SCRIPTS_DIR) \ @@ -394,24 +396,11 @@ openshell-saw-configure-gateway: .check-saw-name ## Configure openshell CLI for $(SCRIPTS_DIR)/extract-gateway-ca.sh || exit 1; \ echo "Registering gateway '$(OPENSHELL_SAW_NAME)'..."; \ openshell gateway remove $(OPENSHELL_SAW_NAME) 2>/dev/null || true; \ - openshell gateway add "$$GW_URL" --name $(OPENSHELL_SAW_NAME) $$OIDC_OPTS; \ - openshell gateway select $(OPENSHELL_SAW_NAME); \ - echo "Gateway '$(OPENSHELL_SAW_NAME)' configured. Endpoint: $$GW_URL"; \ - OIDC_TOKEN_FILE="$(OIDC_TOKEN_DIR)/token.json"; \ - GW_TOKEN_DIR="$$GW_CONFIG_DIR"; \ - if [ -f "$$OIDC_TOKEN_FILE" ] && [ -n "$$OIDC_ISSUER" ]; then \ - echo "Copying OIDC token to gateway config..."; \ - mkdir -p "$$GW_TOKEN_DIR"; \ - chmod 700 "$$GW_TOKEN_DIR"; \ - python3 -c " \ -import json; \ -t = json.load(open('$$OIDC_TOKEN_FILE')); \ -gt = {'access_token': t['access_token'], 'refresh_token': t.get('refresh_token',''), 'issuer': t.get('issuer_url',''), 'client_id': '$(OIDC_CLIENT_ID)'}; \ -json.dump(gt, open('$$GW_TOKEN_DIR/oidc_token.json','w'))" 2>/dev/null && \ - chmod 600 "$$GW_TOKEN_DIR/oidc_token.json" 2>/dev/null && \ - echo "Token configured." || \ - echo "Token copy skipped (already authenticated via gateway login)."; \ - fi + openshell gateway add "$$GW_URL" --name $(OPENSHELL_SAW_NAME) $$OIDC_OPTS || exit 1; \ + openshell gateway select $(OPENSHELL_SAW_NAME) || exit 1; \ + echo "Gateway '$(OPENSHELL_SAW_NAME)' configured. Endpoint: $$GW_URL" +# Keep the token saved by `openshell gateway add`. The separate make-login token +# may belong to another cluster and must not overwrite this gateway's login. openshell-saw-list: ## List all sandboxes (every SAW namespace) @printf "%-20s %-24s %-12s %-10s %s\n" "NAME" "NAMESPACE" "STATUS" "VM" "UPDATED" diff --git a/README.md b/README.md index 36cff20ff..8ce37272f 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Deploy isolated, per-user AI agent sandboxes on OpenShift Virtualization with OI - [Option A: Validated Pattern (automated, GitOps)](#option-a-validated-pattern-automated-gitops) - [Option B: Quickstart (manual, step-by-step)](#option-b-quickstart-manual-step-by-step) - [Supported inference providers](#supported-inference-providers) + - [Custom inference provider](#custom-inference-provider) - [Validating the deployment](#validating-the-deployment) - [Delete](#delete) - [Repository structure](#repository-structure) @@ -46,6 +47,8 @@ This quickstart implements NVIDIA's [Secure Agent Workspace reference architectu The system supports multiple inference providers (Gemini, Anthropic, OpenAI, NVIDIA Build, OpenRouter, Ollama, or custom endpoints) and optional web search integration (Tavily, Brave). A bootc-based golden image pipeline pre-bakes all packages into a container image that CDI imports directly, enabling fast VM provisioning without cloud-init package installation. +For a self-hosted OpenAI-compatible endpoint (vLLM, Ollama, ...), see [Custom inference provider](#custom-inference-provider). + ### Architecture diagrams The following diagrams are from the [NVIDIA Secure Agent Workspace OpenShift Virtualization Reference Implementation](https://docs.nvidia.com/enterprise-reference-architectures/secure-agent-workspace-reference-design/latest/openshift-virtualization-reference-implementation.html). @@ -312,7 +315,37 @@ You can set `OPENSHELL_SAW_NAME` once via `export` and all `openshell-saw-*` tar | NVIDIA Build | `build` | `meta/llama-3.3-70b-instruct` | | OpenRouter | `openrouter` | `anthropic/claude-sonnet-4-6` | | Ollama (local) | `ollama` | `llama3` | -| Custom endpoint | `custom` | any (set `ENDPOINT_URL`) | +| Custom OpenAI-compatible endpoint (vLLM, Ollama, ...) | `openai` + `ENDPOINT_URL` | the model the server serves; see [Custom inference provider](#custom-inference-provider) | + +#### Custom inference provider + +Use a model server of your own (vLLM, Ollama, or any OpenAI-compatible API) instead of a cloud provider. The SAW uses OpenShell's [inference routing](https://github.com/NVIDIA/OpenShell/blob/v0.0.116/docs/sandboxes/inference-routing.mdx): the installer creates an `openai` provider with the endpoint's base URL and sets it as the workspace's inference route. Agents call `https://inference.local/v1`; the gateway adds the key, so it never enters a sandbox. + +Select the `custom-inference` SAW-BOM profile and give the endpoint's URL, model and key. + +**Option A (Validated Pattern)** — in `~/values-secret-secure-agent-workspace.yaml`, use the commented custom example of the `inference` secret (`provider: openai`, `model`, `url`, `api_key`), and select the profile in `charts/saw-bom/values.yaml` (committed to the branch the pattern deploys): + +```yaml +profiles: + - custom-inference +``` + +**Option B (Quickstart)** — one command: + +```bash +make openshell-saw-create OPENSHELL_SAW_NAME=alice PROFILES=custom-inference \ + PROVIDER=openai MODEL= \ + ENDPOINT_URL=http://vllm..svc:8000/v1 \ + API_KEY= # any non-empty value if the server needs no key +``` + +Notes: + +- The **gateway VM** calls the URL, not your laptop: use a cluster Service or Route host. `localhost` is refused. +- With governance on, the `openai` provider type must be in the governance catalog (`charts/governance-policy/profiles/openai.yaml`, shipped with the chart). +- Self-hosted models can be slow; the profile sets a 300-second inference timeout. + +Details: [docs/custom-inference.md](docs/custom-inference.md). ### Validating the deployment diff --git a/charts/governance-policy/profiles/openai.yaml b/charts/governance-policy/profiles/openai.yaml new file mode 100644 index 000000000..ba54e6042 --- /dev/null +++ b/charts/governance-policy/profiles/openai.yaml @@ -0,0 +1,18 @@ +id: openai +display_name: OpenAI-compatible endpoint +description: Any OpenAI-compatible API (OpenAI, vLLM, Ollama, ...) used through inference routing +provider_type: openai +inference_capable: true +credentials: + - name: api_key + description: API key for the endpoint (any non-empty value if it needs none) + env_vars: [OPENAI_API_KEY] + required: true + auth_style: bearer + header_name: authorization +discovery: + credentials: [api_key] +# No endpoints: sandboxes reach the model only through https://inference.local, +# where the gateway's inference router calls the provider's OPENAI_BASE_URL. +# A sandbox attached to this provider gets no direct egress from it. +endpoints: [] diff --git a/charts/openshell-saw/files/installer/apply_bom.py b/charts/openshell-saw/files/installer/apply_bom.py index 3d8ee7e29..a711d03e8 100644 --- a/charts/openshell-saw/files/installer/apply_bom.py +++ b/charts/openshell-saw/files/installer/apply_bom.py @@ -44,6 +44,7 @@ from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from pathlib import Path +from urllib.parse import urlsplit import yaml @@ -96,6 +97,14 @@ "tavily": "TAVILY_API_KEY", } SANDBOX_TYPES = {"generic", "openclaw", "nemoclaw"} +# Provider config key that holds the upstream base URL for OpenShell's +# inference router (openshell-core inference profiles). An `openai` provider +# with OPENAI_BASE_URL reaches any OpenAI-compatible server (vLLM, Ollama, ...). +BASE_URL_CONFIG_KEYS = { + "openai": "OPENAI_BASE_URL", + "anthropic": "ANTHROPIC_BASE_URL", + "nvidia": "NVIDIA_BASE_URL", +} class InstallerError(Exception): @@ -319,6 +328,11 @@ class Provider: credential_secret: str = "" credential_secret_key: str = "api_key" model: str = "" + # Secret keys the base URL and the model are read from (optional). + base_url_secret_key: str = "" + model_secret_key: str = "" + inference_timeout: int = 0 + base_url: str = "" @dataclass @@ -411,7 +425,10 @@ def parse_profiles(files): nemoclaw_provider=p.get("nemoclawProvider", ""), credential_secret=p.get("credentialSecret", ""), credential_secret_key=p.get("credentialSecretKey", "api_key"), - model=p.get("model", ""))) + model=p.get("model", ""), + base_url_secret_key=p.get("baseUrlSecretKey", ""), + model_secret_key=p.get("modelSecretKey", ""), + inference_timeout=int(p.get("inferenceTimeout", 0) or 0))) if "sandbox.yaml" in docs: key, text = docs["sandbox.yaml"] for s in (_yaml(text, key).get("spec") or {}).get("sandboxes") or []: @@ -461,6 +478,15 @@ def validate_profiles(profiles): errors.append(f"{where}: provider '{p.name}' has an invalid credentialSecret name") if not SECRET_KEY_RE.match(p.credential_secret_key or ""): errors.append(f"{where}: provider '{p.name}' has an invalid credentialSecretKey") + for field_name, value in (("baseUrlSecretKey", p.base_url_secret_key), + ("modelSecretKey", p.model_secret_key)): + if value and not SECRET_KEY_RE.match(value): + errors.append(f"{where}: provider '{p.name}' has an invalid {field_name}") + if p.base_url_secret_key and p.type not in BASE_URL_CONFIG_KEYS: + errors.append(f"{where}: provider '{p.name}' of type '{p.type}' does not take a base URL " + f"(supported: {', '.join(sorted(BASE_URL_CONFIG_KEYS))})") + if p.inference_timeout < 0: + errors.append(f"{where}: provider '{p.name}' has a negative inferenceTimeout") sandbox_names = set() for s in ws.sandboxes: if not s.enabled: @@ -535,10 +561,51 @@ def resolve_credentials(profiles, secrets_dir): type_file = base / "provider" configured = type_file.read_text(encoding="utf-8").strip() if type_file.is_file() else "" check_provider_type(p, configured) + if p.model_secret_key: + p.model = read_secret_value(base, p.model_secret_key) or p.model + if p.base_url_secret_key: + p.base_url = read_secret_value(base, p.base_url_secret_key) + if p.base_url: + try: + p.base_url = check_base_url(p.base_url) + except ValueError as exc: + raise InstallerError(f"provider '{p.name}' in workspace '{ws.name}': {exc} " + f"(Secret '{p.credential_secret}' key " + f"'{p.base_url_secret_key}')") from None creds.setdefault(ws.name, {})[p.name] = value return creds +def read_secret_value(base, key): + try: + return (Path(base) / key).read_text(encoding="utf-8").strip() + except OSError: + return "" + + +def check_base_url(url): + """An http(s) base URL without credentials, query or fragment. The value + is not echoed in errors: a pasted URL may contain a token.""" + try: + parts = urlsplit(url) + ok = (parts.scheme in ("http", "https") and parts.hostname + and parts.username is None and parts.password is None + and not parts.query and not parts.fragment + and not any(c.isspace() for c in url)) + if ok: + parts.port # raises ValueError on a bad port + except ValueError: + ok = False + if not ok: + raise ValueError("base URL must be http(s)://host[:port][/path] without credentials, " + "query or fragment") + host = parts.hostname + if host in ("localhost", "127.0.0.1", "::1"): + raise ValueError("base URL must not be localhost: the gateway, not the sandbox, " + "calls it (use a cluster Service or Route host)") + return url.rstrip("/") + + # --------------------------------------------------------------------------- # State (what is installed) # --------------------------------------------------------------------------- @@ -876,6 +943,19 @@ def sync_gateway_config(inputs, cfg, etc_dir, home, owner=None, dry_run=False): # Profile application (runtime user, mTLS only) # --------------------------------------------------------------------------- +def openclaw_replacement_profile(output): + """The credential id in OpenClaw's "Replacement credential saved but + inactive ... openclaw models auth activate --agent main" message + (approach from #50), or None. Only a well-formed id is accepted: the + value is used in a shell command.""" + text = re.sub(r"\x1b\[[0-9;]*m", "", output) + if "Replacement credential saved but inactive" not in text: + return None + ids = re.findall(r"openclaw models auth activate ([a-z0-9][a-z0-9_.-]*:setup-[0-9a-f]{8}-" + r"[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}) --agent main", text) + return ids[0] if len(set(ids)) == 1 else None + + def ws_args(name): return [] if name == "default" else ["--workspace", name] @@ -989,8 +1069,12 @@ def apply_provider(self, ws, provider): credential = self.creds[ws.name][provider.name] env_name = PROVIDER_CRED_MAP[provider.type] env = {env_name: credential} + # OpenAI-compatible (and other) endpoints: the inference router reads + # the upstream base URL from the provider config. + config = (("--config", f"{BASE_URL_CONFIG_KEYS[provider.type]}={provider.base_url}") + if provider.base_url else ()) create = ("provider", "create", "--name", provider.name, "--type", provider.type, - *ws_args(ws.name), "--credential", env_name) + *ws_args(ws.name), "--credential", env_name, *config) created = self.cli(*create, env=env, ok_if_exists=True, check=False) if (not created.ok and NO_PROFILE_RE.search(created.out + " " + created.err) and provider.type in self.provider_profiles): @@ -1007,7 +1091,7 @@ def apply_provider(self, ws, provider): f"'{ws.name}' (openshell provider create failed)") if created.existed: updated = self.cli("provider", "update", provider.name, *ws_args(ws.name), - "--credential", env_name, env=env, check=False) + "--credential", env_name, *config, env=env, check=False) if not updated.ok: log(f"WARN: could not refresh the credential of existing provider '{provider.name}'") @@ -1031,24 +1115,27 @@ def apply_inference(self, ws): if not chosen: return log(f"Inference for '{ws.name}': {chosen.name} / {chosen.model}") + timeout = ("--timeout", str(chosen.inference_timeout)) if chosen.inference_timeout else () self.cli("inference", "set", "--provider", chosen.name, "--model", chosen.model, - "--workspace", ws.name, "--no-verify") + "--workspace", ws.name, *timeout, "--no-verify") # The system route must point at a provider in the 'default' # workspace (the gateway looks it up there), so only that workspace # sets it. if ws.name == SYSTEM_WORKSPACE: self.cli("inference", "set", "--system", "--provider", chosen.name, - "--model", chosen.model, "--no-verify") + "--model", chosen.model, *timeout, "--no-verify") # -- sandboxes ------------------------------------------------------- def find_provider(self, ws, names): - enabled = self.usable(ws) - for name in names or []: - for p in enabled: - if p.name == name: - return p - return enabled[0] if enabled else None + """The provider an agent sandbox is onboarded with: one of the + sandbox's own providers, preferring one with a model. Never another + provider of the workspace: found live, a skipped `custom` provider + made OpenClaw onboard with `brave` and a default NVIDIA model.""" + usable = self.usable(ws) + if names: + usable = [p for n in names for p in usable if p.name == n] + return next((p for p in usable if p.model), usable[0] if usable else None) def sandbox_state(self, ws, sb): """'running', 'broken' (Error/Completed) or 'missing'.""" @@ -1065,6 +1152,7 @@ def create_sandbox(self, ws, sb): self.cli("sandbox", "delete", sb.name, *ws_args(ws.name), check=False) elif state == "running": log(f"Sandbox '{sb.name}' already exists") + self.attach_missing_providers(ws, sb) return if sb.image and ("/" in sb.image or ":" in sb.image): self.sh.run(["podman", "pull", sb.image], check=False, timeout=900) @@ -1081,6 +1169,21 @@ def create_sandbox(self, ws, sb): args += ["--no-tty", "--detach", "--", "sh", "-c", "sleep infinity"] self.cli(*args, timeout=900) + def attach_missing_providers(self, ws, sb): + """A sandbox created while one of its providers was skipped (e.g. no + provider profile yet) gets it once it exists. Found live: the + sandbox kept running without `custom` after the profile arrived.""" + if not sb.providers: + return + listed = self.cli("sandbox", "provider", "list", sb.name, *ws_args(ws.name), + check=False, quiet=True) + attached = set(re.sub(r"\x1b\[[0-9;]*m", "", listed.out).split()) + for prov in sb.providers: + if prov in attached or (ws.name, prov) in self.skipped: + continue + log(f"Attaching provider '{prov}' to existing sandbox '{sb.name}'") + self.cli("sandbox", "provider", "attach", sb.name, prov, *ws_args(ws.name), check=False) + def onboard_nemoclaw(self, ws, sb, provider): home = Path(os.environ.get("HOME", "/home/cloud-user")) mgmt_path = home / "gateway-management.json" @@ -1138,12 +1241,20 @@ def start_openclaw(self, ws, sb, provider): model = sb.model or provider.model or "nvidia/nemotron-3-super-120b-a12b" oc_env = ("OPENCLAW_HOME=/sandbox SQLITE_TMPDIR=/sandbox/.openclaw/state " "TMPDIR=/sandbox/.openclaw/state OPENCLAW_NIX_MODE=0") - self.cli(*exec_cmd, "sh", "-c", + onboarded = self.cli(*exec_cmd, "sh", "-c", f"{oc_env} CUSTOM_API_KEY=proxy-managed openclaw onboard --non-interactive " "--accept-risk --mode local --auth-choice custom-api-key " '--custom-base-url "https://inference.local/v1" ' f"--custom-provider-id {provider.type} --custom-model-id \"{model}\" " "--custom-compatibility openai --skip-channels --skip-health", check=False) + # Re-onboarding an existing sandbox with a different provider or model + # (e.g. after switching to a custom endpoint) makes OpenClaw save the + # new credential but keep the old connection; activate the new one. + profile_id = openclaw_replacement_profile(onboarded.out + "\n" + onboarded.err) + if profile_id: + log(f"Activating the new OpenClaw credential '{profile_id}'") + self.cli(*exec_cmd, "sh", "-c", + f"{oc_env} openclaw models auth activate {profile_id} --agent main", check=False) self.cli(*exec_cmd, "sh", "-c", f"{oc_env} openclaw config set gateway.auth.token '{token}'", check=False) route = self.cfg.get("sandboxDashboardRoute") @@ -1245,6 +1356,14 @@ def verify(self, profiles): if not ran.ok: detail = (ran.err or ran.out).strip().splitlines()[-1:] or [f"exit {ran.rc}"] failures.append(f"openclaw cannot run in sandbox '{sb.name}': {detail[0]}") + if sb.type in ("openclaw", "nemoclaw") and sb.providers and \ + self.find_provider(ws, sb.providers) is None: + # All of the agent's providers were skipped (e.g. no + # provider profile for their type): it has no model. + skipped = ", ".join(f"{p.name} ({p.type})" for p in ws.providers + if p.name in sb.providers) + failures.append(f"{sb.type} sandbox '{sb.name}' in '{ws.name}' has no usable " + f"provider: skipped {skipped}; the gateway has no profile for that type") if sb.providers: attached = self.cli("sandbox", "provider", "list", sb.name, *ws_args(ws.name), check=False, quiet=True).out diff --git a/charts/openshell-saw/files/provider-profiles/openai.yaml b/charts/openshell-saw/files/provider-profiles/openai.yaml new file mode 100644 index 000000000..ba54e6042 --- /dev/null +++ b/charts/openshell-saw/files/provider-profiles/openai.yaml @@ -0,0 +1,18 @@ +id: openai +display_name: OpenAI-compatible endpoint +description: Any OpenAI-compatible API (OpenAI, vLLM, Ollama, ...) used through inference routing +provider_type: openai +inference_capable: true +credentials: + - name: api_key + description: API key for the endpoint (any non-empty value if it needs none) + env_vars: [OPENAI_API_KEY] + required: true + auth_style: bearer + header_name: authorization +discovery: + credentials: [api_key] +# No endpoints: sandboxes reach the model only through https://inference.local, +# where the gateway's inference router calls the provider's OPENAI_BASE_URL. +# A sandbox attached to this provider gets no direct egress from it. +endpoints: [] diff --git a/charts/pattern-secrets/templates/inference-secret.yaml b/charts/pattern-secrets/templates/inference-secret.yaml index 762b3fefa..2647ea03f 100644 --- a/charts/pattern-secrets/templates/inference-secret.yaml +++ b/charts/pattern-secrets/templates/inference-secret.yaml @@ -11,20 +11,12 @@ spec: name: inference template: type: Opaque + engineVersion: v2 data: provider: {{ printf "{{ .provider }}" | quote }} model: {{ printf "{{ .model }}" | quote }} api_key: {{ printf "{{ .api_key }}" | quote }} - data: - - secretKey: provider - remoteRef: + url: {{ printf "{{ index . \"url\" | default \"\" }}" | quote }} + dataFrom: + - extract: key: {{ .Values.vaultPrefix }}/inference - property: provider - - secretKey: model - remoteRef: - key: {{ .Values.vaultPrefix }}/inference - property: model - - secretKey: api_key - remoteRef: - key: {{ .Values.vaultPrefix }}/inference - property: api_key diff --git a/charts/saw-bom/profiles/custom-inference/default/providers.yaml b/charts/saw-bom/profiles/custom-inference/default/providers.yaml new file mode 100644 index 000000000..5692a8986 --- /dev/null +++ b/charts/saw-bom/profiles/custom-inference/default/providers.yaml @@ -0,0 +1,22 @@ +apiVersion: saw.redhat.com/v1alpha1 +kind: Providers +metadata: + profile: custom-inference +spec: + providers: + # OpenShell's `openai` provider type reaches any OpenAI-compatible server: + # the gateway's inference router calls OPENAI_BASE_URL with the key, and + # sandboxes use https://inference.local/v1 without ever seeing the key. + # The base URL and model come from the `inference` Secret (provider: openai). + - name: custom + type: openai + credentialSecret: inference + credentialSecretKey: api_key + baseUrlSecretKey: url + modelSecretKey: model + # Self-hosted models can take longer than OpenShell's 60 s default. + inferenceTimeout: 300 + - name: brave + type: brave + credentialSecret: web-search + credentialSecretKey: api_key diff --git a/charts/saw-bom/profiles/custom-inference/default/sandbox.yaml b/charts/saw-bom/profiles/custom-inference/default/sandbox.yaml new file mode 100644 index 000000000..1aa8af0ac --- /dev/null +++ b/charts/saw-bom/profiles/custom-inference/default/sandbox.yaml @@ -0,0 +1,11 @@ +apiVersion: saw.redhat.com/v1alpha1 +kind: Sandboxes +metadata: {} +spec: + sandboxes: + - name: notebook + type: openclaw + enabled: true + image: quay.io/rh-ai-quickstart/openclaw-openshell:latest + providers: + - custom diff --git a/charts/saw-bom/profiles/custom-inference/default/workspace.yaml b/charts/saw-bom/profiles/custom-inference/default/workspace.yaml new file mode 100644 index 000000000..3d83e7c0e --- /dev/null +++ b/charts/saw-bom/profiles/custom-inference/default/workspace.yaml @@ -0,0 +1,7 @@ +apiVersion: saw.redhat.com/v1alpha1 +kind: Workspace +metadata: + name: default + description: Agent workspace backed by a custom OpenAI-compatible endpoint (vLLM, Ollama, ...) +spec: + enabled: true diff --git a/docs/custom-inference.md b/docs/custom-inference.md new file mode 100644 index 000000000..4fb1817f3 --- /dev/null +++ b/docs/custom-inference.md @@ -0,0 +1,61 @@ +# Custom inference endpoint (vLLM, Ollama, any OpenAI-compatible server) + +A SAW can use a model server of your own instead of a cloud provider. It uses +OpenShell's [inference routing](https://github.com/NVIDIA/OpenShell/blob/v0.0.116/docs/sandboxes/inference-routing.mdx): + +- The installer creates an `openai` provider with the endpoint's base URL + (`--config OPENAI_BASE_URL=`) and the key (passed via the environment), + then sets the workspace inference route (`openshell inference set`). +- The gateway's inference router calls the endpoint with the key. Sandboxes + call `https://inference.local/v1` and never see the key or the endpoint. +- OpenClaw is onboarded against `inference.local`, exactly like the default + NVIDIA setup, so the dashboard, keepalive and verification are unchanged. + +## Configure + +1. Use the `custom-inference` SAW-BOM profile instead of `data-science` + (saw-bom values, e.g. `overrides/saw-bom.yaml`): + + ```yaml + profiles: + - custom-inference + ``` + +2. Put the endpoint in the `inference` Secret (pattern: `~/values-secret-*.yaml`, + see `values-secret.yaml.template`). With the quickstart, one command does + steps 1 and 2: + + ```bash + make openshell-saw-create OPENSHELL_SAW_NAME= PROFILES=custom-inference \ + PROVIDER=openai MODEL= ENDPOINT_URL=https:///v1 API_KEY= + ``` + + The Secret's keys: + + | Key | Value | + |---|---| + | `provider` | `openai` (OpenShell's provider type for any OpenAI-compatible API) | + | `model` | the model name the server serves, e.g. `meta-llama/Llama-3.1-8B-Instruct` | + | `url` | the OpenAI-compatible base URL, ending in `/v1` | + | `api_key` | the server's key; any non-empty value if it needs none | + +3. Restart the VM (`make openshell-saw-restart`) so the installer applies it. + +## Requirements + +- The **gateway VM** must reach the URL, not your laptop: use a cluster Service + (`http://vllm..svc:8000/v1`) or Route host. `localhost` is refused. +- `url` must be `http(s)://host[:port][/path]` without credentials, query or + fragment. The installer rejects anything else without logging the value. +- With governance on, the gateway only accepts provider types from the + governance catalog, so `charts/governance-policy/profiles/openai.yaml` must + be deployed (a profile the installer imports itself is not enough). The + profile has no endpoints: sandboxes get no direct egress from it. +- Self-hosted models can be slow: the profile sets `inferenceTimeout: 300` + seconds (OpenShell's default is 60). + +## Limitations + +- One inference route per workspace (an OpenShell limitation). +- NemoClaw sandboxes onboard their own provider settings; the profile only + ships an OpenClaw sandbox. diff --git a/docs/versioned-bom-installer.md b/docs/versioned-bom-installer.md index 390c9eff5..ab670f26f 100644 --- a/docs/versioned-bom-installer.md +++ b/docs/versioned-bom-installer.md @@ -174,3 +174,11 @@ make test-installer # installer + chart tests; chart tests need helm - Migrating VMs created by the old SSH-based chart in place: cloud-init has already run on them, so the installer units are never written. Recreate the VM (delete the VM and its `-root` DataVolume) after upgrading the chart. + +## Custom inference + +A self-hosted OpenAI-compatible endpoint (vLLM, Ollama, ...) is an `openai` +provider with `OPENAI_BASE_URL` plus the workspace inference route, as in +OpenShell's inference routing docs. Select the `custom-inference` SAW-BOM +profile and put `provider: openai`, `model`, `url` and `api_key` in the +`inference` Secret; see [Custom inference](custom-inference.md). diff --git a/scripts/openshell-saw-create.sh b/scripts/openshell-saw-create.sh index 761c61bdd..8fabd1560 100755 --- a/scripts/openshell-saw-create.sh +++ b/scripts/openshell-saw-create.sh @@ -4,7 +4,12 @@ # Required env vars: OPENSHELL_SAW_NAME, SAW_CHART # Required env vars (provider): PROVIDER + MODEL + API_KEY, or GCP_SA_JSON # Optional: OWNER, OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_TOKEN_DIR, NS, SAW_NS, -# KEYCLOAK_NS, AGENT, ENDPOINT_URL, WEB_SEARCH, SCRIPTS_DIR +# KEYCLOAK_NS, AGENT, ENDPOINT_URL, WEB_SEARCH, SCRIPTS_DIR, +# PROFILES (comma-separated SAW-BOM profiles, default: the chart's) +# +# Custom OpenAI-compatible endpoint (vLLM, Ollama, ...): +# PROVIDER=openai MODEL= ENDPOINT_URL=https:///v1 \ +# API_KEY= PROFILES=custom-inference # # Each SAW gets its own namespace (SAW_NS, default saw-). The shared # namespace NS keeps the golden image and the governance interceptor. @@ -29,6 +34,7 @@ PROVIDER="${PROVIDER:-}" MODEL="${MODEL:-}" API_KEY="${API_KEY:-}" ENDPOINT_URL="${ENDPOINT_URL:-}" +PROFILES="${PROFILES:-}" WEB_SEARCH="${WEB_SEARCH:-}" GCP_SA_JSON="${GCP_SA_JSON:-}" OIDC_ISSUER="${OIDC_ISSUER:-}" @@ -136,6 +142,7 @@ if [[ -n "${API_KEY}" ]]; then --from-literal=api_key="${API_KEY}" \ ${PROVIDER:+--from-literal=provider="${PROVIDER}"} \ ${MODEL:+--from-literal=model="${MODEL}"} \ + ${ENDPOINT_URL:+--from-literal=url="${ENDPOINT_URL}"} \ --dry-run=client -o yaml | oc apply -f - >/dev/null echo "Secret 'inference' updated in ${DEPLOY_NS}." fi @@ -150,8 +157,16 @@ fi # --- SAW-BOM profiles --- # The VM can only attach ConfigMaps from its own namespace, so each SAW gets # its own saw-bom-profiles ConfigMap. -helm upgrade --install saw-bom "${SAW_BOM_CHART}" --namespace "${DEPLOY_NS}" >/dev/null -echo "SAW-BOM profiles installed in ${DEPLOY_NS}." +BOM_OPTS=() +if [[ -n "${PROFILES}" ]]; then + BOM_VALUES="$(mktemp)" + trap 'rm -f "${BOM_VALUES}"' EXIT + { echo "profiles:"; tr ',' '\n' <<<"${PROFILES}" | sed -e 's/^ *//' -e 's/ *$//' -e '/^$/d' -e 's/^/ - /'; } > "${BOM_VALUES}" + BOM_OPTS=(-f "${BOM_VALUES}") +fi +# ${arr[@]+...}: an empty array is "unbound" under set -u in bash < 4.4 (macOS). +helm upgrade --install saw-bom "${SAW_BOM_CHART}" --namespace "${DEPLOY_NS}" ${BOM_OPTS[@]+"${BOM_OPTS[@]}"} >/dev/null +echo "SAW-BOM profiles installed in ${DEPLOY_NS}${PROFILES:+ (${PROFILES})}." # --- Deploy --- echo "Provisioning sandbox '${OPENSHELL_SAW_NAME}' for owner '${OWNER}' in namespace '${DEPLOY_NS}'..." diff --git a/tests/charts/test_openshell_saw_chart.py b/tests/charts/test_openshell_saw_chart.py index 751d2b583..9f3779e6b 100644 --- a/tests/charts/test_openshell_saw_chart.py +++ b/tests/charts/test_openshell_saw_chart.py @@ -604,7 +604,7 @@ def test_governance_profiles_carry_their_id(): def test_installer_profile_copies_match_governance_policy(): copies = sorted(SAW_PROFILES.glob("*.yaml")) - assert [p.name for p in copies] == ["brave.yaml"] + assert [p.name for p in copies] == ["brave.yaml", "openai.yaml"] for path in copies: assert path.read_text() == (GOVERNANCE_PROFILES / path.name).read_text(), path.name @@ -614,7 +614,7 @@ def test_installer_disk_ships_provider_profiles(default_docs, ab, tmp_path): assert data["provider-profile-brave.yaml"] == (SAW_PROFILES / "brave.yaml").read_text() for key, value in data.items(): (tmp_path / key).write_text(value) - assert set(ab.provider_profiles(tmp_path)) == {"brave"} + assert set(ab.provider_profiles(tmp_path)) == {"brave", "openai"} def test_prepare_job_reads_the_admin_secret_of_the_keycloak_in_use(): @@ -649,6 +649,48 @@ def test_secret_template_matches_the_default_profile(): assert configured in (p["type"], p.get("nemoclawProvider")), (p["name"], configured) +def test_custom_inference_profile_validates_in_the_shipped_installer(tmp_path): + """saw-bom `profiles: [custom-inference]` with an `inference` Secret for a + custom OpenAI-compatible endpoint (provider/model/url/api_key).""" + values = tmp_path / "saw-bom.yaml" + values.write_text("profiles: [custom-inference]\n") + result = helm_template(BOM_CHART, "-f", str(values)) + assert result.returncode == 0, result.stderr + [cm] = [d for d in yaml.safe_load_all(result.stdout) if d] + assert all("__custom-inference__" in k for k in cm["data"]) + docs = render(*PATTERN_SAW_SETTINGS) + run_saw = tmp_path / "run-saw" + for key, value in installer_data(docs).items(): + (run_saw / "installer").mkdir(parents=True, exist_ok=True) + (run_saw / "installer" / key).write_text(value) + for key, value in cm["data"].items(): + (run_saw / "profiles").mkdir(exist_ok=True) + (run_saw / "profiles" / key).write_text(value) + for secret, data in {"inference": {"api_key": "k1", "provider": "openai", "model": "m", + "url": "https://vllm.models.svc:8443/v1"}, + "web-search": {"api_key": "k2"}}.items(): + (run_saw / "secrets" / secret).mkdir(parents=True) + for key, value in data.items(): + (run_saw / "secrets" / secret / key).write_text(value) + result = subprocess.run([sys.executable, str(run_saw / "installer" / "apply_bom.py"), + "validate", "--inputs", str(run_saw)], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + assert "1 workspace(s) ['default']" in result.stdout + + +def test_inference_secret_carries_an_optional_url(): + """The ExternalSecret reads every key of the Vault entry; `url` is + optional so cloud-provider entries without it keep working.""" + result = helm_template(ROOT / "charts" / "pattern-secrets") + assert result.returncode == 0, result.stderr + es = next(d for d in yaml.safe_load_all(result.stdout) if d and d["metadata"]["name"] == "inference") + assert es["spec"]["dataFrom"] == [{"extract": {"key": "secret/data/hub/inference"}}] + assert "data" not in es["spec"] + tmpl = es["spec"]["target"]["template"]["data"] + assert set(tmpl) == {"provider", "model", "api_key", "url"} + assert tmpl["url"] == '{{ index . "url" | default "" }}' + + def test_cleanup_hook_can_be_turned_off(): """helm uninstall (and deleting the Argo CD app) deletes the VM through a pre-delete hook unless cleanupOnDelete is false.""" diff --git a/tests/installer/fakes/openshell b/tests/installer/fakes/openshell index a87bd1c53..9a43b6749 100755 --- a/tests/installer/fakes/openshell +++ b/tests/installer/fakes/openshell @@ -120,11 +120,17 @@ elif op == "provider create": if key in state["providers"]: fail(f"Error: provider {opt('--name')} already exists") state["providers"][key] = {"type": opt("--type"), "credential": credential()} + configs = [head[i + 1] for i, a in enumerate(head) if a == "--config"] + if configs: + state["providers"][key]["config"] = configs elif op == "provider update": key = f"{ws}/{head[2]}" if key not in state["providers"]: fail("Error: provider not found") state["providers"][key]["credential"] = credential() + configs = [head[i + 1] for i, a in enumerate(head) if a == "--config"] + if configs: + state["providers"][key]["config"] = configs elif op == "provider get": if f"{ws}/{head[2]}" not in state["providers"]: fail("Error: provider not found") @@ -156,6 +162,20 @@ elif op == "sandbox exec": if (state_dir / "exec-fail.json").exists() else []) if opt("-n") in failing: fail("sh: line 1: /usr/local/sbin/openclaw: Permission denied", 126) + # exec-output.json: {"": ""} + outputs = (json.loads((state_dir / "exec-output.json").read_text()) + if (state_dir / "exec-output.json").exists() else {}) + for needle, text in outputs.items(): + if needle in " ".join(args): + print(text, file=sys.stderr) +elif op == "sandbox provider" and head[2] == "attach": + sb = state["sandboxes"].get(f"{ws}/{head[3]}") + if not sb: + fail("Error: sandbox not found") + if f"{ws}/{head[4]}" not in state["providers"]: + fail(f"Error: provider '{head[4]}' not found") + if head[4] not in sb["providers"]: + sb["providers"].append(head[4]) elif op == "sandbox provider": sb = state["sandboxes"].get(f"{ws}/{head[3]}") for p in (sb or {}).get("providers", []): diff --git a/tests/installer/test_custom_endpoint.py b/tests/installer/test_custom_endpoint.py new file mode 100644 index 000000000..3fe79250d --- /dev/null +++ b/tests/installer/test_custom_endpoint.py @@ -0,0 +1,175 @@ +"""A custom OpenAI-compatible endpoint (vLLM, Ollama, ...) through OpenShell's +inference router: an `openai` provider with OPENAI_BASE_URL, the workspace +inference route, and sandboxes on https://inference.local/v1.""" + +import pytest + +from conftest import profile_files + +URL = "https://vllm.models.svc.cluster.local:8443/v1" +MODEL = "meta-llama/Llama-3.1-8B-Instruct" + + +@pytest.fixture +def custom_secrets(secrets_dir): + inference = secrets_dir / "inference" + for key, value in {"provider": "openai", "api_key": "sk-CUSTOM-TEST-KEY", + "url": URL + "/", "model": MODEL}.items(): + (inference / key).write_text(value + "\n") + return secrets_dir + + +@pytest.fixture +def profiles(ab): + return ab.parse_profiles(profile_files("custom-inference")) + + +def test_profile_is_valid_and_reads_url_and_model_from_the_secret(ab, profiles, custom_secrets): + ab.validate_profiles(profiles) + creds = ab.resolve_credentials(profiles, custom_secrets) + custom = next(p for p in profiles[0].workspaces[0].providers if p.name == "custom") + assert (custom.type, custom.base_url, custom.model) == ("openai", URL, MODEL) + assert creds["default"]["custom"] == "sk-CUSTOM-TEST-KEY" + + +def test_apply_creates_an_openai_provider_and_the_inference_route(ab, fake_env, config, profiles, + custom_secrets): + creds = ab.resolve_credentials(profiles, custom_secrets) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) + state = fake_env.openshell_state() + assert state["providers"]["default/custom"] == { + "type": "openai", "credential": "OPENAI_API_KEY=sk-CUSTOM-TEST-KEY", + "config": [f"OPENAI_BASE_URL={URL}"]} + assert state["inference"]["default"] == ["custom", MODEL] + assert state["system_inference"] == ["custom", MODEL] + sets = [c for c in fake_env.openshell_calls() if c[:2] == ["inference", "set"]] + assert sets and all(c[c.index("--timeout") + 1] == "300" for c in sets) + # The key only ever travels in the environment. + assert not any("sk-CUSTOM-TEST-KEY" in " ".join(c) for c in fake_env.openshell_calls()) + # OpenClaw is onboarded against inference.local, not the endpoint itself. + onboard = next(" ".join(c) for c in fake_env.openshell_calls() if "onboard" in " ".join(c)) + assert "https://inference.local/v1" in onboard and URL not in onboard + assert f'--custom-model-id "{MODEL}"' in onboard + + +def test_rerun_updates_the_base_url(ab, fake_env, config, profiles, custom_secrets): + creds = ab.resolve_credentials(profiles, custom_secrets) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) + (custom_secrets / "inference" / "url").write_text("http://ollama.models.svc:11434/v1\n") + profiles2 = ab.parse_profiles(profile_files("custom-inference")) + creds = ab.resolve_credentials(profiles2, custom_secrets) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles2) + assert fake_env.openshell_state()["providers"]["default/custom"]["config"] == [ + "OPENAI_BASE_URL=http://ollama.models.svc:11434/v1"] + + +@pytest.mark.parametrize("url", ["ftp://host/v1", "https://user:pw@host/v1", "https://host/v1?key=x", + "https://host/v1#f", "http://localhost:8000/v1", "https://host:99999/v1", + "not a url"]) +def test_bad_base_urls_are_refused_without_echoing_them(ab, profiles, custom_secrets, url): + (custom_secrets / "inference" / "url").write_text(url) + with pytest.raises(ab.InstallerError) as err: + ab.resolve_credentials(profiles, custom_secrets) + assert url not in str(err.value) and "base URL" in str(err.value) + + +def test_a_secret_for_another_provider_still_fails(ab, profiles, custom_secrets): + """Selecting a profile is explicit (saw-bom `profiles`); a mismatched + Secret is still an error, never a silent skip.""" + (custom_secrets / "inference" / "provider").write_text("gemini\n") + with pytest.raises(ab.InstallerError, match="is for 'gemini'"): + ab.resolve_credentials(profiles, custom_secrets) + + +def test_the_secret_names_the_openshell_provider_type(ab, profiles, custom_secrets): + """There is no `custom` provider type in OpenShell: the Secret says + `openai`, the type the gateway creates.""" + (custom_secrets / "inference" / "provider").write_text("custom\n") + with pytest.raises(ab.InstallerError, match="expects a openai credential"): + ab.resolve_credentials(profiles, custom_secrets) + + +def test_base_url_only_for_types_the_router_supports(ab): + files = profile_files("custom-inference") + key = next(k for k in files if k.endswith("providers.yaml")) + files[key] = files[key].replace("type: openai", "type: gemini") + with pytest.raises(ab.InstallerError, match="does not take a base URL"): + ab.validate_profiles(ab.parse_profiles(files)) + + +def test_data_science_profile_is_unchanged(ab, shipped_profile_files, secrets_dir): + """No url/model keys in the Secret: providers keep their profile model.""" + profiles = ab.parse_profiles(shipped_profile_files) + ab.resolve_credentials(profiles, secrets_dir) + nvidia = next(p for p in profiles[0].workspaces[0].providers if p.name == "nvidia") + assert (nvidia.base_url, nvidia.model) == ("", "nvidia/nemotron-3-super-120b-a12b") + + +def test_without_an_openai_profile_the_agent_is_not_onboarded_with_another_provider( + ab, fake_env, config, profiles, custom_secrets): + """Found live with governance on: `openai` had no provider profile, the + provider was skipped, and OpenClaw was onboarded with `brave` and a + default NVIDIA model while verification passed.""" + fake_env.without_profiles("openai") + creds = ab.resolve_credentials(profiles, custom_secrets) + applier = ab.ProfileApplier(ab.Shell(), config, creds) + applier.apply(profiles) + calls = [" ".join(c) for c in fake_env.openshell_calls()] + assert not any("onboard" in c for c in calls) + failures = applier.verify(profiles) + assert any("has no usable provider" in f and "custom (openai)" in f for f in failures), failures + + +def test_the_shipped_openai_profile_is_imported_when_the_gateway_lacks_it( + ab, fake_env, config, profiles, custom_secrets, tmp_path): + """Governance off: the installer imports its copy of the `openai` profile.""" + from pathlib import Path + fake_env.without_profiles("openai") + shipped = Path(__file__).resolve().parents[2] / "charts/openshell-saw/files/provider-profiles/openai.yaml" + creds = ab.resolve_credentials(profiles, custom_secrets) + applier = ab.ProfileApplier(ab.Shell(), config, creds, {"openai": shipped.read_text()}) + applier.apply(profiles) + assert fake_env.openshell_state()["providers"]["default/custom"]["type"] == "openai" + assert applier.verify(profiles) == [] + + +def test_a_provider_that_arrives_later_is_attached_to_the_existing_sandbox( + ab, fake_env, config, profiles, custom_secrets): + """Found live: boot 1 had no `openai` profile, so `notebook` was created + without `custom`; after the profile reached the catalog, boot 2 created + the provider but left the running sandbox without it.""" + fake_env.without_profiles("openai") + creds = ab.resolve_credentials(profiles, custom_secrets) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) + assert fake_env.openshell_state()["sandboxes"]["default/notebook"]["providers"] == [] + (fake_env.state / "no-profiles.json").write_text("[]") # the catalog now has it + applier = ab.ProfileApplier(ab.Shell(), config, creds) + applier.apply(profiles) + assert fake_env.openshell_state()["sandboxes"]["default/notebook"]["providers"] == ["custom"] + assert applier.verify(profiles) == [] + + +REPLACED = ("error: Replacement credential saved but inactive. Your connection is unchanged. " + "Test and activate it with:\nopenclaw models auth activate " + "openai:setup-df67c47c-d3f2-46f5-b698-c42390c67b5d --agent main") + + +def test_a_replaced_openclaw_credential_is_activated(ab, fake_env, config, profiles, custom_secrets): + """Found live: re-onboarding the existing notebook for the custom + endpoint left OpenClaw on its previous connection.""" + import json + (fake_env.state / "exec-output.json").write_text(json.dumps({"openclaw onboard": REPLACED})) + creds = ab.resolve_credentials(profiles, custom_secrets) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) + calls = [" ".join(c) for c in fake_env.openshell_calls()] + assert any("openclaw models auth activate openai:setup-df67c47c-d3f2-46f5-b698-c42390c67b5d --agent main" + in c for c in calls) + + +@pytest.mark.parametrize("output", [ + "Onboarding complete", + "Replacement credential saved but inactive.\nopenclaw models auth activate x;rm -rf / --agent main", + REPLACED + "\nopenclaw models auth activate openai:setup-00000000-0000-0000-0000-000000000000 --agent main", +]) +def test_replacement_parsing_is_strict(ab, output): + assert ab.openclaw_replacement_profile(output) is None diff --git a/tests/scripts/test_gateway_login_token.py b/tests/scripts/test_gateway_login_token.py new file mode 100644 index 000000000..950680221 --- /dev/null +++ b/tests/scripts/test_gateway_login_token.py @@ -0,0 +1,44 @@ +"""Gateway configuration must retain the token obtained for that gateway.""" +import json +import os +from pathlib import Path +import subprocess + +import pytest + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest.mark.parametrize('cached_issuer', ['https://old-cluster/realms/openshell', 'https://new-cluster/realms/openshell']) +def test_configure_keeps_gateway_login_token(tmp_path, cached_issuer): + home = tmp_path / 'home' + cached = home / '.config/openshell/oidc' + cached.mkdir(parents=True) + (cached / 'token.json').write_text(json.dumps({'issuer_url': cached_issuer, 'access_token': 'stale-token'})) + scripts = tmp_path / 'scripts' + scripts.mkdir() + ca = scripts / 'extract-gateway-ca.sh' + ca.write_text('#!/bin/sh\nmkdir -p "$(dirname "$OUT_FILE")"\nprintf ca > "$OUT_FILE"\n') + ca.chmod(0o755) + fakebin = tmp_path / 'bin' + fakebin.mkdir() + oc = fakebin / 'oc' + oc.write_text('#!/bin/sh\nprintf https://new-gateway\n') + oc.chmod(0o755) + cli = fakebin / 'openshell' + cli.write_text('''#!/bin/sh +if [ "$1 $2" = "gateway add" ]; then + mkdir -p "$HOME/.config/openshell/gateways/test" + printf '{"access_token":"fresh-token"}' > "$HOME/.config/openshell/gateways/test/oidc_token.json" +fi +''') + cli.chmod(0o755) + env = dict(os.environ, HOME=str(home), PATH=f'{fakebin}:{os.environ["PATH"]}') + result = subprocess.run(['make', '-f', str(ROOT / 'Makefile-quickstart'), + 'openshell-saw-configure-gateway', 'OPENSHELL_SAW_NAME=test', + 'OIDC_ISSUER=https://new-cluster/realms/openshell', + f'OIDC_TOKEN_DIR={cached}', f'SCRIPTS_DIR={scripts}/'], + cwd=ROOT, env=env, capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + saved = json.loads((home / '.config/openshell/gateways/test/oidc_token.json').read_text()) + assert saved['access_token'] == 'fresh-token' diff --git a/tests/scripts/test_saw_create_custom_inference.py b/tests/scripts/test_saw_create_custom_inference.py new file mode 100644 index 000000000..fc353692a --- /dev/null +++ b/tests/scripts/test_saw_create_custom_inference.py @@ -0,0 +1,76 @@ +"""scripts/openshell-saw-create.sh with fake oc/helm: ENDPOINT_URL goes into +the inference Secret's `url`, PROFILES selects the SAW-BOM profiles.""" +import os +import subprocess +from pathlib import Path + +import pytest +import yaml + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "scripts" / "openshell-saw-create.sh" + +FAKE_OC = r'''#!/usr/bin/env bash +echo "oc $*" >> "$FAKE_LOG" +case "$1" in + whoami) echo admin ;; + create) echo "kind: Secret # $*" ;; # --dry-run=client -o yaml + apply) cat >> "$FAKE_LOG" ;; +esac +exit 0 +''' +FAKE_HELM = r'''#!/usr/bin/env bash +echo "helm $*" >> "$FAKE_LOG" +prev="" +for a in "$@"; do + if [[ "$prev" == "-f" ]]; then cp "$a" "$FAKE_DIR/bom-values.yaml"; fi + prev="$a" +done +exit 0 +''' + + +@pytest.fixture +def run(tmp_path): + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + for name, body in (("oc", FAKE_OC), ("helm", FAKE_HELM)): + (bin_dir / name).write_text(body) + (bin_dir / name).chmod(0o755) + scripts = tmp_path / "scripts" + scripts.mkdir() + (scripts / "keycloak-host.sh").write_text("#!/bin/sh\nexit 1\n") + (scripts / "keycloak-host.sh").chmod(0o755) + log = tmp_path / "log" + + def _run(**env): + full = {**os.environ, "PATH": f"{bin_dir}:{os.environ['PATH']}", "FAKE_LOG": str(log), + "FAKE_DIR": str(tmp_path), "OPENSHELL_SAW_NAME": "cinf", "SAW_CHART": "charts/openshell-saw", + "OWNER": "alice", "OIDC_ISSUER": "none", "SCRIPTS_DIR": str(scripts), **env} + result = subprocess.run(["bash", str(SCRIPT)], env=full, cwd=ROOT, capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + return log.read_text(), tmp_path / "bom-values.yaml" + return _run + + +def test_custom_endpoint_and_profile(run): + log, bom_values = run(PROVIDER="openai", MODEL="m", API_KEY="k", + ENDPOINT_URL="https://vllm.models.svc:8443/v1", PROFILES="custom-inference") + secret = next(line for line in log.splitlines() if line.startswith("oc create secret generic inference")) + assert "--from-literal=url=https://vllm.models.svc:8443/v1" in secret + assert "--from-literal=provider=openai" in secret + assert yaml.safe_load(bom_values.read_text()) == {"profiles": ["custom-inference"]} + + +def test_several_profiles(run): + _, bom_values = run(PROVIDER="build", MODEL="m", API_KEY="k", PROFILES="data-science, custom-inference") + assert yaml.safe_load(bom_values.read_text()) == {"profiles": ["data-science", "custom-inference"]} + + +def test_defaults_are_unchanged(run): + log, bom_values = run(PROVIDER="build", MODEL="m", API_KEY="k") + secret = next(line for line in log.splitlines() if line.startswith("oc create secret generic inference")) + assert "url=" not in secret + assert not bom_values.exists() + bom = next(line for line in log.splitlines() if line.startswith("helm upgrade --install saw-bom")) + assert " -f " not in bom diff --git a/values-secret.yaml.template b/values-secret.yaml.template index 403349935..c2f7124bf 100644 --- a/values-secret.yaml.template +++ b/values-secret.yaml.template @@ -32,6 +32,17 @@ secrets: value: nvidia/nemotron-3-super-120b-a12b - name: api_key path: ~/.nvidia-api-key + # Custom OpenAI-compatible endpoint (vLLM, Ollama, ...): set saw-bom + # `profiles: [custom-inference]` and use these fields instead. OpenShell + # uses an `openai` provider with this base URL (see docs/custom-inference.md): + # - name: provider + # value: openai + # - name: model + # value: meta-llama/Llama-3.1-8B-Instruct + # - name: url + # value: https://vllm.models.svc.cluster.local:8443/v1 + # - name: api_key + # path: ~/.custom-inference-api-key # any non-empty value if the server needs no key # --- Web search --- # The default profile creates a `brave` provider in the default workspace,