spaider-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- spaider_cli/__init__.py +14 -0
- spaider_cli/commands/__init__.py +6 -0
- spaider_cli/commands/agent.py +178 -0
- spaider_cli/commands/doctor.py +231 -0
- spaider_cli/commands/init.py +405 -0
- spaider_cli/commands/mcp.py +193 -0
- spaider_cli/lib/__init__.py +10 -0
- spaider_cli/lib/api.py +160 -0
- spaider_cli/lib/docker.py +117 -0
- spaider_cli/lib/env.py +135 -0
- spaider_cli/lib/llm.py +87 -0
- spaider_cli/lib/mcp.py +285 -0
- spaider_cli/main.py +71 -0
- spaider_cli/skills/__init__.py +8 -0
- spaider_cli/skills/claude_code.md +151 -0
- spaider_cli-0.1.0.dist-info/METADATA +121 -0
- spaider_cli-0.1.0.dist-info/RECORD +21 -0
- spaider_cli-0.1.0.dist-info/WHEEL +5 -0
- spaider_cli-0.1.0.dist-info/entry_points.txt +2 -0
- spaider_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
- spaider_cli-0.1.0.dist-info/top_level.txt +1 -0
spaider_cli/lib/api.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""HTTP client for the SpAIder REST API.
|
|
2
|
+
|
|
3
|
+
Thin wrapper over httpx that exposes only the endpoints the CLI needs. All
|
|
4
|
+
calls target ``${SPAIDER_API_BASE:-http://localhost:8000/api/v1}`` by default.
|
|
5
|
+
|
|
6
|
+
The local dev API does not require authentication for /agents endpoints; the
|
|
7
|
+
client therefore makes unauthenticated calls. If the user is targeting a
|
|
8
|
+
deployment behind Kong with auth enforced (production / managed Cloud), a
|
|
9
|
+
future ``--api-key`` flag on the CLI will be plumbed through here.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
DEFAULT_API_BASE = "http://localhost:8000/api/v1"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def api_base() -> str:
|
|
23
|
+
"""Resolve the API base URL from the environment, with a localhost default."""
|
|
24
|
+
return os.environ.get("SPAIDER_API_BASE", DEFAULT_API_BASE).rstrip("/")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class SpaiderApiError(RuntimeError):
|
|
28
|
+
"""Raised when the SpAIder API returns a non-2xx response or is unreachable."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Agent:
|
|
33
|
+
"""Subset of the SpAIder Agent shape that the CLI cares about."""
|
|
34
|
+
id: str
|
|
35
|
+
name: str
|
|
36
|
+
api_key: str | None = None # only populated on create / rotate
|
|
37
|
+
description: str | None = None
|
|
38
|
+
tenant_id: str = "default"
|
|
39
|
+
clearance_level: int = 1
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def from_payload(cls, data: dict[str, Any]) -> "Agent":
|
|
43
|
+
return cls(
|
|
44
|
+
id=data.get("id", ""),
|
|
45
|
+
name=data.get("name", ""),
|
|
46
|
+
api_key=data.get("api_key"),
|
|
47
|
+
description=data.get("description"),
|
|
48
|
+
tenant_id=data.get("tenant_id", "default"),
|
|
49
|
+
clearance_level=int(data.get("clearance_level", 1)),
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _client(timeout: float = 10.0) -> httpx.Client:
|
|
54
|
+
return httpx.Client(base_url=api_base(), timeout=timeout)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def health() -> bool:
|
|
58
|
+
"""Return True iff the SpAIder API is reachable and reports healthy.
|
|
59
|
+
|
|
60
|
+
Uses a short timeout so the doctor command doesn't hang when the backend
|
|
61
|
+
isn't running.
|
|
62
|
+
"""
|
|
63
|
+
try:
|
|
64
|
+
with httpx.Client(timeout=2.0) as c:
|
|
65
|
+
resp = c.get(f"{api_base().rsplit('/api', 1)[0]}/health")
|
|
66
|
+
return resp.status_code == 200 and resp.json().get("healthy") is True
|
|
67
|
+
except Exception:
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def embedding_health() -> dict | None:
|
|
72
|
+
"""GET /health/embedding — embedding-dimension consistency report.
|
|
73
|
+
|
|
74
|
+
Returns the report dict (``expected_dims``/``present_dims``/``consistent``…)
|
|
75
|
+
or ``None`` when the backend isn't reachable. Slightly longer timeout than
|
|
76
|
+
``health()`` since the backend scans for distinct vector sizes.
|
|
77
|
+
"""
|
|
78
|
+
try:
|
|
79
|
+
with httpx.Client(timeout=5.0) as c:
|
|
80
|
+
resp = c.get(f"{api_base().rsplit('/api', 1)[0]}/health/embedding")
|
|
81
|
+
if resp.status_code == 200:
|
|
82
|
+
return resp.json()
|
|
83
|
+
except Exception:
|
|
84
|
+
return None
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def list_agents() -> list[Agent]:
|
|
89
|
+
"""GET /agents — list every agent."""
|
|
90
|
+
try:
|
|
91
|
+
with _client() as c:
|
|
92
|
+
resp = c.get("/agents")
|
|
93
|
+
resp.raise_for_status()
|
|
94
|
+
payload = resp.json()
|
|
95
|
+
except httpx.HTTPError as exc:
|
|
96
|
+
raise SpaiderApiError(f"list_agents failed: {exc}") from exc
|
|
97
|
+
return [Agent.from_payload(a) for a in payload.get("agents", [])]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def find_agent_by_name(name: str) -> Agent | None:
|
|
101
|
+
"""Return the first agent whose name matches, or None."""
|
|
102
|
+
for a in list_agents():
|
|
103
|
+
if a.name == name:
|
|
104
|
+
return a
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def create_agent(
|
|
109
|
+
name: str,
|
|
110
|
+
*,
|
|
111
|
+
description: str | None = None,
|
|
112
|
+
tenant_id: str = "default",
|
|
113
|
+
clearance_level: int = 1,
|
|
114
|
+
) -> Agent:
|
|
115
|
+
"""POST /agents — creates a new agent. Returns the created agent (with api_key)."""
|
|
116
|
+
body: dict[str, Any] = {
|
|
117
|
+
"name": name,
|
|
118
|
+
"tenant_id": tenant_id,
|
|
119
|
+
"permissions": ["read", "write", "query"],
|
|
120
|
+
"clearance_level": clearance_level,
|
|
121
|
+
}
|
|
122
|
+
if description:
|
|
123
|
+
body["description"] = description
|
|
124
|
+
try:
|
|
125
|
+
with _client() as c:
|
|
126
|
+
resp = c.post("/agents", json=body)
|
|
127
|
+
resp.raise_for_status()
|
|
128
|
+
payload = resp.json()
|
|
129
|
+
except httpx.HTTPError as exc:
|
|
130
|
+
raise SpaiderApiError(f"create_agent({name!r}) failed: {exc}") from exc
|
|
131
|
+
return Agent.from_payload(payload.get("agent", {}))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def rotate_key(agent_id: str) -> str:
|
|
135
|
+
"""POST /agents/{id}/rotate-key — returns the new raw API key.
|
|
136
|
+
|
|
137
|
+
The key is shown exactly once; the backend only stores its SHA-256 hash
|
|
138
|
+
after this call returns.
|
|
139
|
+
"""
|
|
140
|
+
try:
|
|
141
|
+
with _client() as c:
|
|
142
|
+
resp = c.post(f"/agents/{agent_id}/rotate-key")
|
|
143
|
+
resp.raise_for_status()
|
|
144
|
+
payload = resp.json()
|
|
145
|
+
except httpx.HTTPError as exc:
|
|
146
|
+
raise SpaiderApiError(f"rotate_key({agent_id}) failed: {exc}") from exc
|
|
147
|
+
key = payload.get("api_key")
|
|
148
|
+
if not key:
|
|
149
|
+
raise SpaiderApiError(f"rotate_key({agent_id}) returned no api_key")
|
|
150
|
+
return key
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def delete_agent(agent_id: str) -> None:
|
|
154
|
+
"""DELETE /agents/{id} — removes the agent and all its graph data."""
|
|
155
|
+
try:
|
|
156
|
+
with _client() as c:
|
|
157
|
+
resp = c.delete(f"/agents/{agent_id}")
|
|
158
|
+
resp.raise_for_status()
|
|
159
|
+
except httpx.HTTPError as exc:
|
|
160
|
+
raise SpaiderApiError(f"delete_agent({agent_id}) failed: {exc}") from exc
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Docker detection + stack lifecycle for ``spaider init``.
|
|
2
|
+
|
|
3
|
+
Surface intentionally narrow — we only need:
|
|
4
|
+
|
|
5
|
+
- ``check_docker_available()``: is the ``docker`` CLI installed AND the daemon running?
|
|
6
|
+
- ``compose_up(repo_root)``: bring up ``docker compose -f ... -f docker-compose.dev.yml up -d backend-api``.
|
|
7
|
+
- ``wait_for_backend(timeout)``: poll ``http://localhost:8000/health`` until it returns ``healthy: true``.
|
|
8
|
+
|
|
9
|
+
All subprocess calls go through ``subprocess.run`` with explicit ``capture_output``
|
|
10
|
+
so we don't leak Docker progress noise into the rich-printed wizard UI.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import httpx
|
|
21
|
+
|
|
22
|
+
# ---------------------------------------------------------------------------
|
|
23
|
+
# Detection
|
|
24
|
+
# ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class DockerStatus:
|
|
29
|
+
cli_present: bool
|
|
30
|
+
daemon_running: bool
|
|
31
|
+
error: str | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def check_docker_available() -> DockerStatus:
|
|
35
|
+
"""Inspect Docker's state without raising.
|
|
36
|
+
|
|
37
|
+
Returns ``cli_present`` and ``daemon_running``. Caller decides what to do
|
|
38
|
+
on red — e.g. ``spaider init`` blocks with an actionable message; ``spaider doctor``
|
|
39
|
+
just reports.
|
|
40
|
+
"""
|
|
41
|
+
if shutil.which("docker") is None:
|
|
42
|
+
return DockerStatus(cli_present=False, daemon_running=False)
|
|
43
|
+
try:
|
|
44
|
+
result = subprocess.run(
|
|
45
|
+
["docker", "info"],
|
|
46
|
+
capture_output=True,
|
|
47
|
+
text=True,
|
|
48
|
+
timeout=5,
|
|
49
|
+
)
|
|
50
|
+
except (subprocess.TimeoutExpired, OSError) as exc:
|
|
51
|
+
return DockerStatus(cli_present=True, daemon_running=False, error=str(exc))
|
|
52
|
+
if result.returncode != 0:
|
|
53
|
+
return DockerStatus(
|
|
54
|
+
cli_present=True,
|
|
55
|
+
daemon_running=False,
|
|
56
|
+
error=(result.stderr or result.stdout or "").strip()[:200],
|
|
57
|
+
)
|
|
58
|
+
return DockerStatus(cli_present=True, daemon_running=True)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ---------------------------------------------------------------------------
|
|
62
|
+
# Compose lifecycle
|
|
63
|
+
# ---------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class ComposeResult:
|
|
68
|
+
ok: bool
|
|
69
|
+
stdout: str
|
|
70
|
+
stderr: str
|
|
71
|
+
returncode: int
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def compose_up(repo_root: Path, service: str = "backend-api") -> ComposeResult:
|
|
75
|
+
"""Bring up the dev stack via ``docker compose -f ... up -d <service>``."""
|
|
76
|
+
cmd = [
|
|
77
|
+
"docker", "compose",
|
|
78
|
+
"-f", str(repo_root / "docker-compose.yml"),
|
|
79
|
+
"-f", str(repo_root / "docker-compose.dev.yml"),
|
|
80
|
+
"up", "-d", service,
|
|
81
|
+
]
|
|
82
|
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
|
83
|
+
return ComposeResult(
|
|
84
|
+
ok=result.returncode == 0,
|
|
85
|
+
stdout=result.stdout,
|
|
86
|
+
stderr=result.stderr,
|
|
87
|
+
returncode=result.returncode,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ---------------------------------------------------------------------------
|
|
92
|
+
# Healthcheck
|
|
93
|
+
# ---------------------------------------------------------------------------
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def wait_for_backend(
|
|
97
|
+
*,
|
|
98
|
+
base_url: str = "http://localhost:8000",
|
|
99
|
+
timeout_s: float = 120.0,
|
|
100
|
+
poll_interval_s: float = 2.0,
|
|
101
|
+
) -> bool:
|
|
102
|
+
"""Poll the ``/health`` endpoint until it reports healthy or we time out.
|
|
103
|
+
|
|
104
|
+
Returns True if the backend went healthy within the budget. Does not raise
|
|
105
|
+
on per-poll errors — the wait loop swallows transient connect-refused.
|
|
106
|
+
"""
|
|
107
|
+
deadline = time.monotonic() + timeout_s
|
|
108
|
+
while time.monotonic() < deadline:
|
|
109
|
+
try:
|
|
110
|
+
with httpx.Client(timeout=2.0) as c:
|
|
111
|
+
resp = c.get(f"{base_url}/health")
|
|
112
|
+
if resp.status_code == 200 and resp.json().get("healthy") is True:
|
|
113
|
+
return True
|
|
114
|
+
except Exception:
|
|
115
|
+
pass
|
|
116
|
+
time.sleep(poll_interval_s)
|
|
117
|
+
return False
|
spaider_cli/lib/env.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""``.env`` file management for ``spaider init``.
|
|
2
|
+
|
|
3
|
+
Two responsibilities:
|
|
4
|
+
|
|
5
|
+
1. **Merge** values into an existing ``.env`` (or create from ``.env.example``)
|
|
6
|
+
without disturbing keys we don't touch. Preserves comments and ordering.
|
|
7
|
+
2. **Generate** the secrets the user shouldn't have to type — JWT signing
|
|
8
|
+
key, connector encryption key, Neo4j password — with the same recipes
|
|
9
|
+
the README documents (so values round-trip with manual setup).
|
|
10
|
+
|
|
11
|
+
Atomic writes via ``spaider_cli.lib.mcp.atomic_write_text`` so partial state
|
|
12
|
+
never lands on disk.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import base64
|
|
17
|
+
import re
|
|
18
|
+
import secrets
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from spaider_cli.lib.mcp import atomic_write_text, backup_if_exists
|
|
22
|
+
|
|
23
|
+
# ---------------------------------------------------------------------------
|
|
24
|
+
# Secret generation — match the README recipes exactly
|
|
25
|
+
# ---------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def generate_jwt_secret() -> str:
|
|
29
|
+
"""64 hex chars (matches ``python -c "import secrets; print(secrets.token_hex(32))"``)."""
|
|
30
|
+
return secrets.token_hex(32)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def generate_connector_key() -> str:
|
|
34
|
+
"""Base64-encoded 32-byte AES key.
|
|
35
|
+
|
|
36
|
+
Matches the README recipe::
|
|
37
|
+
|
|
38
|
+
python -c "import secrets,base64; print(base64.b64encode(secrets.token_bytes(32)).decode())"
|
|
39
|
+
"""
|
|
40
|
+
return base64.b64encode(secrets.token_bytes(32)).decode()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def generate_neo4j_password() -> str:
|
|
44
|
+
"""A friendly password — 24 url-safe characters."""
|
|
45
|
+
return secrets.token_urlsafe(18)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ---------------------------------------------------------------------------
|
|
49
|
+
# .env parsing / writing
|
|
50
|
+
# ---------------------------------------------------------------------------
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# Matches ``KEY=value`` (anchored to the start of a line, allowing whitespace).
|
|
54
|
+
# Captures the key in group 1 for in-place substitution.
|
|
55
|
+
_ASSIGN = re.compile(r"^([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def parse_env_text(text: str) -> dict[str, str]:
|
|
59
|
+
"""Parse a ``.env`` style text blob into a dict of ``KEY: value`` pairs.
|
|
60
|
+
|
|
61
|
+
Comments and blank lines are ignored. The trailing value text is taken
|
|
62
|
+
verbatim — no shell-style quoting is interpreted, which matches what
|
|
63
|
+
``pydantic-settings`` does at runtime.
|
|
64
|
+
"""
|
|
65
|
+
out: dict[str, str] = {}
|
|
66
|
+
for raw_line in text.splitlines():
|
|
67
|
+
stripped = raw_line.lstrip()
|
|
68
|
+
if not stripped or stripped.startswith("#"):
|
|
69
|
+
continue
|
|
70
|
+
match = _ASSIGN.match(stripped)
|
|
71
|
+
if match is None:
|
|
72
|
+
continue
|
|
73
|
+
key, value = match.group(1), match.group(2)
|
|
74
|
+
out[key] = value
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def update_env_text(template: str, overrides: dict[str, str]) -> str:
|
|
79
|
+
"""Return a new .env body with each ``overrides[key]`` substituted in.
|
|
80
|
+
|
|
81
|
+
Preserves comments, blank lines, and the original ordering. Keys that
|
|
82
|
+
appear in ``overrides`` but not in ``template`` are appended at the end
|
|
83
|
+
in insertion order (so the output is deterministic).
|
|
84
|
+
"""
|
|
85
|
+
lines = template.splitlines(keepends=True)
|
|
86
|
+
seen: set[str] = set()
|
|
87
|
+
new_lines: list[str] = []
|
|
88
|
+
for line in lines:
|
|
89
|
+
match = _ASSIGN.match(line.lstrip())
|
|
90
|
+
if match is None:
|
|
91
|
+
new_lines.append(line)
|
|
92
|
+
continue
|
|
93
|
+
key = match.group(1)
|
|
94
|
+
if key in overrides:
|
|
95
|
+
seen.add(key)
|
|
96
|
+
newline = "\n" if line.endswith("\n") else ""
|
|
97
|
+
new_lines.append(f"{key}={overrides[key]}{newline}")
|
|
98
|
+
else:
|
|
99
|
+
new_lines.append(line)
|
|
100
|
+
|
|
101
|
+
extras = [k for k in overrides if k not in seen]
|
|
102
|
+
if extras:
|
|
103
|
+
# Ensure trailing newline before appending
|
|
104
|
+
if new_lines and not new_lines[-1].endswith("\n"):
|
|
105
|
+
new_lines[-1] = new_lines[-1] + "\n"
|
|
106
|
+
new_lines.append("\n# ── added by `spaider init` ─────────────────────\n")
|
|
107
|
+
for key in extras:
|
|
108
|
+
new_lines.append(f"{key}={overrides[key]}\n")
|
|
109
|
+
return "".join(new_lines)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def write_env_file(
|
|
113
|
+
*,
|
|
114
|
+
target: Path,
|
|
115
|
+
example: Path,
|
|
116
|
+
overrides: dict[str, str],
|
|
117
|
+
) -> Path | None:
|
|
118
|
+
"""Write ``target`` based on ``example`` with ``overrides`` applied.
|
|
119
|
+
|
|
120
|
+
If ``target`` already exists, it's read in (preserving any custom values)
|
|
121
|
+
and ``overrides`` are merged on top. The previous version is backed up.
|
|
122
|
+
|
|
123
|
+
Returns the path of the backup file (or ``None`` if no backup was made).
|
|
124
|
+
"""
|
|
125
|
+
if not example.exists():
|
|
126
|
+
raise FileNotFoundError(f"missing .env.example at {example}")
|
|
127
|
+
if target.exists():
|
|
128
|
+
template = target.read_text(encoding="utf-8")
|
|
129
|
+
else:
|
|
130
|
+
template = example.read_text(encoding="utf-8")
|
|
131
|
+
|
|
132
|
+
backup = backup_if_exists(target)
|
|
133
|
+
new_body = update_env_text(template, overrides)
|
|
134
|
+
atomic_write_text(target, new_body)
|
|
135
|
+
return backup
|
spaider_cli/lib/llm.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""LLM provider key validation for ``spaider init``.
|
|
2
|
+
|
|
3
|
+
Each provider check is a tiny smoke call (1-token completion) that returns a
|
|
4
|
+
strict ``(ok, error_hint)`` pair. The wizard can then re-prompt the user with
|
|
5
|
+
an actionable hint on failure.
|
|
6
|
+
|
|
7
|
+
OpenAI does a live probe (lists models). Anthropic is a format check (`sk-ant-`
|
|
8
|
+
prefix) — a deeper live probe can land later. Ollama checks daemon reachability
|
|
9
|
+
(no key needed). All three are wired into ``spaider init``'s provider menu.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class KeyCheckResult:
|
|
20
|
+
ok: bool
|
|
21
|
+
detail: str # short human-readable hint when not ok; "" when ok
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def validate_openai_key(api_key: str, *, timeout_s: float = 10.0) -> KeyCheckResult:
|
|
25
|
+
"""Confirm an OpenAI API key works by listing models.
|
|
26
|
+
|
|
27
|
+
Listing models is cheaper than running a completion (no token billing) and
|
|
28
|
+
a 200 response is sufficient to confirm both the key format and quota.
|
|
29
|
+
"""
|
|
30
|
+
if not api_key or not api_key.startswith("sk-"):
|
|
31
|
+
return KeyCheckResult(
|
|
32
|
+
ok=False,
|
|
33
|
+
detail="OpenAI keys start with 'sk-'. Get one at https://platform.openai.com/api-keys.",
|
|
34
|
+
)
|
|
35
|
+
try:
|
|
36
|
+
with httpx.Client(timeout=timeout_s) as c:
|
|
37
|
+
resp = c.get(
|
|
38
|
+
"https://api.openai.com/v1/models",
|
|
39
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
40
|
+
)
|
|
41
|
+
except httpx.HTTPError as exc:
|
|
42
|
+
return KeyCheckResult(ok=False, detail=f"network error talking to OpenAI: {exc}")
|
|
43
|
+
|
|
44
|
+
if resp.status_code == 200:
|
|
45
|
+
return KeyCheckResult(ok=True, detail="")
|
|
46
|
+
if resp.status_code == 401:
|
|
47
|
+
return KeyCheckResult(
|
|
48
|
+
ok=False,
|
|
49
|
+
detail="OpenAI rejected the key (401). Likely typo or revoked key.",
|
|
50
|
+
)
|
|
51
|
+
if resp.status_code == 429:
|
|
52
|
+
return KeyCheckResult(
|
|
53
|
+
ok=False,
|
|
54
|
+
detail="OpenAI returned 429 — key is valid but you're rate limited or out of quota.",
|
|
55
|
+
)
|
|
56
|
+
return KeyCheckResult(
|
|
57
|
+
ok=False,
|
|
58
|
+
detail=f"OpenAI returned status {resp.status_code}: {resp.text[:120]}",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def validate_anthropic_key(api_key: str) -> KeyCheckResult:
|
|
63
|
+
"""Anthropic key validation — format check (``sk-ant-`` prefix)."""
|
|
64
|
+
if not api_key.startswith("sk-ant-"):
|
|
65
|
+
return KeyCheckResult(
|
|
66
|
+
ok=False,
|
|
67
|
+
detail="Anthropic keys start with 'sk-ant-'. Get one at https://console.anthropic.com/.",
|
|
68
|
+
)
|
|
69
|
+
return KeyCheckResult(ok=True, detail="(format-only check)")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def validate_ollama_local(base_url: str = "http://localhost:11434") -> KeyCheckResult:
|
|
73
|
+
"""Confirm a local Ollama daemon is reachable. No key needed."""
|
|
74
|
+
try:
|
|
75
|
+
with httpx.Client(timeout=2.0) as c:
|
|
76
|
+
resp = c.get(f"{base_url}/api/tags")
|
|
77
|
+
if resp.status_code == 200:
|
|
78
|
+
return KeyCheckResult(ok=True, detail="")
|
|
79
|
+
return KeyCheckResult(
|
|
80
|
+
ok=False,
|
|
81
|
+
detail=f"Ollama responded with {resp.status_code}.",
|
|
82
|
+
)
|
|
83
|
+
except httpx.HTTPError as exc:
|
|
84
|
+
return KeyCheckResult(
|
|
85
|
+
ok=False,
|
|
86
|
+
detail=f"Ollama not reachable at {base_url}: {exc}. Start it with `ollama serve`.",
|
|
87
|
+
)
|