relaylm 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.
relaylm/__init__.py ADDED
File without changes
relaylm/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from relaylm.cli.app import app
2
+
3
+ app()
File without changes
@@ -0,0 +1,88 @@
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Any
4
+
5
+
6
+ def _detect_claude_code() -> Path | None:
7
+ claude_settings = Path.home() / ".claude" / "settings.json"
8
+ if claude_settings.exists():
9
+ return claude_settings
10
+ return None
11
+
12
+
13
+ def _detect_opencode() -> Path | None:
14
+ opencode_config = Path.home() / ".config" / "opencode" / "opencode.json"
15
+ if opencode_config.exists():
16
+ return opencode_config
17
+ return None
18
+
19
+
20
+ def _configure_claude_code(config_path: Path, endpoint_url: str, dry_run: bool) -> bool:
21
+ try:
22
+ content = json.loads(config_path.read_text())
23
+ except (json.JSONDecodeError, FileNotFoundError):
24
+ content = {}
25
+
26
+ content["apiProvider"] = "anthropic"
27
+ content["customApiUrl"] = endpoint_url
28
+
29
+ if dry_run:
30
+ return True
31
+
32
+ config_path.write_text(json.dumps(content, indent=2))
33
+ return True
34
+
35
+
36
+ def _configure_opencode(config_path: Path, endpoint_url: str, dry_run: bool) -> bool:
37
+ try:
38
+ content = json.loads(config_path.read_text())
39
+ except (json.JSONDecodeError, FileNotFoundError):
40
+ content = {}
41
+
42
+ content["model"] = endpoint_url.rstrip("/") + "/chat/completions"
43
+
44
+ if dry_run:
45
+ return True
46
+
47
+ config_path.write_text(json.dumps(content, indent=2))
48
+ return True
49
+
50
+
51
+ def detect_and_configure_agents(
52
+ endpoint_url: str, dry_run: bool = False
53
+ ) -> list[dict[str, Any]]:
54
+ results: list[dict[str, Any]] = []
55
+
56
+ claude_config = _detect_claude_code()
57
+ if claude_config:
58
+ _configure_claude_code(claude_config, endpoint_url, dry_run)
59
+ action = "Would configure" if dry_run else "Configured"
60
+ results.append(
61
+ {
62
+ "agent": "claude-code",
63
+ "config_path": str(claude_config),
64
+ "action": action,
65
+ }
66
+ )
67
+ else:
68
+ results.append(
69
+ {"agent": "claude-code", "config_path": None, "action": "Not found"}
70
+ )
71
+
72
+ opencode_config = _detect_opencode()
73
+ if opencode_config:
74
+ _configure_opencode(opencode_config, endpoint_url, dry_run)
75
+ action = "Would configure" if dry_run else "Configured"
76
+ results.append(
77
+ {
78
+ "agent": "opencode",
79
+ "config_path": str(opencode_config),
80
+ "action": action,
81
+ }
82
+ )
83
+ else:
84
+ results.append(
85
+ {"agent": "opencode", "config_path": None, "action": "Not found"}
86
+ )
87
+
88
+ return results
File without changes
relaylm/cli/app.py ADDED
@@ -0,0 +1,233 @@
1
+ import getpass
2
+ from typing import Any
3
+
4
+ import typer
5
+
6
+ app = typer.Typer(
7
+ name="relaylm",
8
+ help="Single-command AI router environment bootstrap",
9
+ no_args_is_help=True,
10
+ )
11
+
12
+ providers_app = typer.Typer(help="Manage external AI providers")
13
+ config_app = typer.Typer(help="Manage RelayLM configuration")
14
+ app.add_typer(providers_app, name="providers")
15
+ app.add_typer(config_app, name="config")
16
+
17
+
18
+ @app.command()
19
+ def setup(
20
+ models: str | None = typer.Option(
21
+ None, "--models", help="Comma-separated model list (overrides auto-detection)"
22
+ ),
23
+ yes: bool = typer.Option(
24
+ False,
25
+ "--yes",
26
+ "--non-interactive",
27
+ help="Auto-accept all prompts (non-interactive mode)",
28
+ ),
29
+ runtime: str | None = typer.Option(
30
+ None, "--runtime", help="Force container runtime: podman or docker"
31
+ ),
32
+ port: int = typer.Option(8000, "--port", help="Router port"),
33
+ ) -> None:
34
+ """Bootstrap the local AI routing environment."""
35
+ from relaylm.config.backup import create_backup
36
+ from relaylm.config.loader import load_config, save_config
37
+ from relaylm.container.runtime import detect_runtime
38
+ from relaylm.hardware.detector import detect
39
+ from relaylm.models.selector import select_models, validate_models
40
+
41
+ hardware = detect()
42
+ typer.echo(f"Detected hardware: {hardware}")
43
+
44
+ if models:
45
+ model_list = [m.strip() for m in models.split(",")]
46
+ invalid = validate_models(model_list)
47
+ if invalid:
48
+ typer.echo(f"Error: Invalid model names: {invalid}", err=True)
49
+ raise typer.Exit(code=2)
50
+ selected_models: list[dict[str, Any]] = [
51
+ {"name": m, "source": "huggingface", "gpu_index": None, "args": {}}
52
+ for m in model_list
53
+ ]
54
+ else:
55
+ selected_models = select_models(hardware)
56
+
57
+ typer.echo(f"Selected models: {[m['name'] for m in selected_models]}")
58
+
59
+ rt = runtime or detect_runtime()
60
+ if rt is None:
61
+ if yes:
62
+ typer.echo(
63
+ "No container runtime found. Install Podman: https://podman.io/docs/installation"
64
+ )
65
+ raise typer.Exit(code=1)
66
+ typer.echo("No container runtime detected.")
67
+ if typer.confirm("Install Podman now?"):
68
+ typer.echo("Installing Podman... (platform-specific)")
69
+ else:
70
+ raise typer.Exit(code=1)
71
+
72
+ typer.echo(f"Using container runtime: {rt}")
73
+
74
+ from relaylm.container.vllm import VLLMManager
75
+
76
+ manager = VLLMManager(runtime=rt)
77
+ use_gpu = hardware.has_nvidia_gpu or hardware.has_amd_gpu
78
+ container_id = manager.deploy([m["name"] for m in selected_models], gpu=use_gpu)
79
+ typer.echo(f"vLLM container started: {container_id}")
80
+ typer.echo(f"Router endpoint: {manager.endpoint_url}")
81
+
82
+ from relaylm.agents.detector import detect_and_configure_agents
83
+
84
+ detect_and_configure_agents(manager.endpoint_url)
85
+
86
+ create_backup()
87
+ config = load_config()
88
+ config["version"] = 1
89
+ config["container_runtime"] = rt
90
+ config["models"] = selected_models
91
+ config.setdefault("fallback", {"order": ["local"], "timeout_seconds": 30})
92
+ config.setdefault("router", {"host": "127.0.0.1", "port": port})
93
+ save_config(config)
94
+
95
+ typer.echo("Configuration saved to ~/.config/relaylm/config.yml")
96
+ typer.echo(f"Setup complete! Router ready at {manager.endpoint_url}")
97
+
98
+
99
+ @providers_app.command()
100
+ def add(
101
+ name: str = typer.Argument(help="Provider name: anthropic or openai"),
102
+ key: str | None = typer.Option(
103
+ None, "--key", help="API key (prompts securely if omitted)"
104
+ ),
105
+ base_url: str | None = typer.Option(None, "--base-url", help="API base URL"),
106
+ yes: bool = typer.Option(False, "--yes", help="Skip confirmation"),
107
+ ) -> None:
108
+ """Configure a new external AI provider."""
109
+ from relaylm.config.backup import create_backup
110
+ from relaylm.config.loader import load_config, save_config
111
+ from relaylm.providers.keychain import store_key
112
+
113
+ if name not in ("anthropic", "openai"):
114
+ typer.echo(
115
+ f"Error: provider must be 'anthropic' or 'openai', got '{name}'", err=True
116
+ )
117
+ raise typer.Exit(code=2)
118
+
119
+ resolved_key = key
120
+ if resolved_key is None and not yes:
121
+ resolved_key = getpass.getpass(f"Enter {name} API key: ")
122
+
123
+ if resolved_key is None:
124
+ typer.echo(
125
+ "Error: API key is required (use --key or enter when prompted)", err=True
126
+ )
127
+ raise typer.Exit(code=2)
128
+
129
+ store_key(f"relaylm-{name}", resolved_key)
130
+ typer.echo(f"API key for {name} stored securely.")
131
+
132
+ create_backup()
133
+ config = load_config()
134
+ config.setdefault("providers", {})
135
+ provider_entry = config["providers"].setdefault(name, {})
136
+ provider_entry["enabled"] = True
137
+ provider_entry["base_url"] = base_url or (
138
+ "https://api.anthropic.com/v1"
139
+ if name == "anthropic"
140
+ else "https://api.openai.com/v1"
141
+ )
142
+ provider_entry["keychain_service"] = f"relaylm-{name}"
143
+ fallback = config.setdefault(
144
+ "fallback", {"order": ["local"], "timeout_seconds": 30}
145
+ )
146
+ if name not in fallback.get("order", []):
147
+ fallback.setdefault("order", ["local"]).append(name)
148
+ save_config(config)
149
+ typer.echo(f"Provider '{name}' configured.")
150
+
151
+
152
+ @providers_app.command()
153
+ def list_cmd() -> None:
154
+ """List configured providers."""
155
+ from relaylm.providers.manager import ProviderManager
156
+
157
+ mgr = ProviderManager()
158
+ providers = mgr.list_providers()
159
+ if not providers:
160
+ typer.echo("No providers configured.")
161
+ return
162
+ for p in providers:
163
+ key_status = "key set" if p["has_key"] else "no key"
164
+ typer.echo(f" {p['name']}: enabled={p['enabled']}, {key_status}")
165
+
166
+
167
+ @config_app.command()
168
+ def show() -> None:
169
+ """Print current configuration (secrets masked)."""
170
+ from relaylm.config.loader import load_config
171
+
172
+ config = load_config()
173
+ if not config:
174
+ typer.echo("No configuration found. Run 'relaylm setup' first.")
175
+ raise typer.Exit(code=1)
176
+ typer.echo(config)
177
+
178
+
179
+ @config_app.command()
180
+ def path() -> None:
181
+ """Print the configuration file path."""
182
+ from relaylm.config.loader import get_config_path
183
+
184
+ typer.echo(str(get_config_path()))
185
+
186
+
187
+ @config_app.command()
188
+ def restore(
189
+ timestamp: str | None = typer.Argument(None, help="Backup timestamp to restore"),
190
+ list_backups: bool = typer.Option(False, "--list", help="List available backups"),
191
+ ) -> None:
192
+ """Restore configuration from a backup."""
193
+ from relaylm.config.backup import list_backups as get_backups
194
+ from relaylm.config.backup import restore_backup
195
+
196
+ if list_backups:
197
+ backups = get_backups()
198
+ if not backups:
199
+ typer.echo("No backups found.")
200
+ return
201
+ for b in backups:
202
+ typer.echo(f" {b['timestamp']}")
203
+ return
204
+
205
+ if timestamp is None:
206
+ typer.echo(
207
+ "Specify a timestamp or use --list to see available backups.", err=True
208
+ )
209
+ raise typer.Exit(code=2)
210
+
211
+ result = restore_backup(timestamp)
212
+ if result is None:
213
+ typer.echo(f"Backup '{timestamp}' not found.", err=True)
214
+ raise typer.Exit(code=1)
215
+ typer.echo(f"Configuration restored from backup '{timestamp}'.")
216
+
217
+
218
+ @app.command()
219
+ def agents(
220
+ dry_run: bool = typer.Option(
221
+ False, "--dry-run", help="Show what would be changed without writing"
222
+ ),
223
+ yes: bool = typer.Option(False, "--yes", help="Apply changes without confirmation"),
224
+ ) -> None:
225
+ """Detect and configure coding agents."""
226
+ from relaylm.agents.detector import detect_and_configure_agents
227
+
228
+ endpoint = "http://127.0.0.1:8000/v1"
229
+ detect_and_configure_agents(endpoint, dry_run=dry_run)
230
+
231
+
232
+ if __name__ == "__main__":
233
+ app()
File without changes
@@ -0,0 +1,37 @@
1
+ from datetime import datetime
2
+ from pathlib import Path
3
+
4
+ from relaylm.config.loader import CONFIG_DIR, CONFIG_PATH
5
+
6
+ BACKUP_DIR = CONFIG_DIR / "backups"
7
+
8
+
9
+ def create_backup() -> Path | None:
10
+ if not CONFIG_PATH.exists():
11
+ return None
12
+ BACKUP_DIR.mkdir(parents=True, exist_ok=True)
13
+ timestamp = datetime.now().strftime("%Y%m%dT%H%M%S")
14
+ backup_path = BACKUP_DIR / f"config-{timestamp}.yml"
15
+ content = CONFIG_PATH.read_bytes()
16
+ backup_path.write_bytes(content)
17
+ return backup_path
18
+
19
+
20
+ def list_backups() -> list[dict[str, str]]:
21
+ if not BACKUP_DIR.exists():
22
+ return []
23
+ backups = []
24
+ for p in sorted(BACKUP_DIR.iterdir(), reverse=True):
25
+ if p.suffix == ".yml":
26
+ backups.append({"timestamp": p.stem.replace("config-", ""), "path": str(p)})
27
+ return backups
28
+
29
+
30
+ def restore_backup(timestamp: str) -> Path | None:
31
+ backup_path = BACKUP_DIR / f"config-{timestamp}.yml"
32
+ if not backup_path.exists():
33
+ return None
34
+ CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
35
+ content = backup_path.read_bytes()
36
+ CONFIG_PATH.write_bytes(content)
37
+ return CONFIG_PATH
@@ -0,0 +1,47 @@
1
+ from pathlib import Path
2
+ from typing import Any
3
+
4
+ import yaml
5
+
6
+ CONFIG_DIR = Path.home() / ".config" / "relaylm"
7
+ CONFIG_PATH = CONFIG_DIR / "config.yml"
8
+
9
+
10
+ def get_config_path() -> Path:
11
+ return CONFIG_PATH
12
+
13
+
14
+ def load_config() -> dict[str, Any]:
15
+ if not CONFIG_PATH.exists():
16
+ return {}
17
+ with open(CONFIG_PATH) as f:
18
+ result = yaml.safe_load(f)
19
+ return result if isinstance(result, dict) else {}
20
+
21
+
22
+ def save_config(config: dict[str, Any]) -> None:
23
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
24
+ with open(CONFIG_PATH, "w") as f:
25
+ yaml.dump(config, f, default_flow_style=False)
26
+
27
+
28
+ def validate_config(config: dict[str, Any]) -> list[str]:
29
+ errors: list[str] = []
30
+ if "version" not in config:
31
+ errors.append("Missing required field: version")
32
+ runtime = config.get("container_runtime")
33
+ if runtime and runtime not in ("podman", "docker"):
34
+ errors.append(f"container_runtime must be 'podman' or 'docker', got: {runtime}")
35
+ models = config.get("models", [])
36
+ for i, m in enumerate(models):
37
+ if not m.get("name"):
38
+ errors.append(f"models[{i}].name is required")
39
+ fallback = config.get("fallback", {})
40
+ order = fallback.get("order", [])
41
+ if (
42
+ order
43
+ and "local" not in order
44
+ and not any(p in order for p in ("anthropic", "openai"))
45
+ ):
46
+ errors.append("fallback.order must include at least one valid target")
47
+ return errors
File without changes
@@ -0,0 +1,79 @@
1
+ import shutil
2
+ import subprocess
3
+
4
+
5
+ def detect_runtime() -> str | None:
6
+ podman_path = shutil.which("podman")
7
+ docker_path = shutil.which("docker")
8
+
9
+ if podman_path:
10
+ try:
11
+ result = subprocess.run(
12
+ [podman_path, "info"], capture_output=True, text=True, timeout=10
13
+ )
14
+ if result.returncode == 0:
15
+ return "podman"
16
+ except (subprocess.TimeoutExpired, FileNotFoundError):
17
+ pass
18
+
19
+ if docker_path:
20
+ try:
21
+ result = subprocess.run(
22
+ [docker_path, "info"], capture_output=True, text=True, timeout=10
23
+ )
24
+ if result.returncode == 0:
25
+ return "docker"
26
+ except (subprocess.TimeoutExpired, FileNotFoundError):
27
+ pass
28
+
29
+ return None
30
+
31
+
32
+ def _runtime_binary(runtime: str) -> str:
33
+ return runtime # "podman" or "docker"
34
+
35
+
36
+ def run_container(
37
+ runtime: str,
38
+ image: str,
39
+ ports: dict[int, int] | None = None,
40
+ volumes: list[str] | None = None,
41
+ gpu: bool = False,
42
+ env: dict[str, str] | None = None,
43
+ extra_args: list[str] | None = None,
44
+ ) -> subprocess.CompletedProcess[str]:
45
+ cmd = [_runtime_binary(runtime), "run", "-d", "--ipc=host"]
46
+ if ports:
47
+ for host_port, container_port in ports.items():
48
+ cmd.extend(["-p", f"{host_port}:{container_port}"])
49
+ if volumes:
50
+ for v in volumes:
51
+ cmd.extend(["-v", v])
52
+ if gpu and runtime == "docker":
53
+ cmd.extend(["--gpus", "all"])
54
+ elif gpu and runtime == "podman":
55
+ cmd.extend(["--device", "nvidia.com/gpu=all"])
56
+ if env:
57
+ for k, v in env.items():
58
+ cmd.extend(["-e", f"{k}={v}"])
59
+ if extra_args:
60
+ cmd.extend(extra_args)
61
+ cmd.extend([image])
62
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=120)
63
+
64
+
65
+ def pull_image(runtime: str, image: str) -> subprocess.CompletedProcess[str]:
66
+ cmd = [_runtime_binary(runtime), "pull", image]
67
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=300)
68
+
69
+
70
+ def stop_container(runtime: str, container_id: str) -> subprocess.CompletedProcess[str]:
71
+ cmd = [_runtime_binary(runtime), "stop", container_id]
72
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=30)
73
+
74
+
75
+ def remove_container(
76
+ runtime: str, container_id: str
77
+ ) -> subprocess.CompletedProcess[str]:
78
+ cmd = [_runtime_binary(runtime), "rm", "-f", container_id]
79
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=30)
@@ -0,0 +1,57 @@
1
+ from pathlib import Path
2
+
3
+ from relaylm.container.runtime import (
4
+ detect_runtime,
5
+ pull_image,
6
+ remove_container,
7
+ run_container,
8
+ stop_container,
9
+ )
10
+
11
+ VLLM_IMAGE = "vllm/vllm-openai:latest"
12
+ VLLM_IMAGE_ROCM = "vllm/vllm-openai-rocm:latest"
13
+ LOCAL_PORT = 8000
14
+ CONTAINER_PORT = 8000
15
+
16
+
17
+ class VLLMManager:
18
+ def __init__(self, runtime: str | None = None):
19
+ detected = runtime or detect_runtime()
20
+ if detected is None:
21
+ raise RuntimeError("No container runtime found (install Podman or Docker)")
22
+ self.runtime: str = detected
23
+
24
+ def deploy(self, model_names: list[str], gpu: bool = False) -> str:
25
+ image = VLLM_IMAGE
26
+ env = {"HF_HOME": "/root/.cache/huggingface"}
27
+
28
+ pull_image(self.runtime, image)
29
+
30
+ volume = f"{Path.home() / '.cache' / 'huggingface'}:/root/.cache/huggingface"
31
+ args = ["--model", model_names[0]]
32
+ for m in model_names[1:]:
33
+ args.extend(["--model", m])
34
+
35
+ result = run_container(
36
+ runtime=self.runtime,
37
+ image=image,
38
+ ports={LOCAL_PORT: CONTAINER_PORT},
39
+ volumes=[volume],
40
+ gpu=gpu,
41
+ env=env,
42
+ extra_args=args,
43
+ )
44
+ if result.returncode != 0:
45
+ raise RuntimeError(
46
+ f"Failed to start vLLM container: {result.stderr.strip()}"
47
+ )
48
+ container_id: str = (result.stdout or "").strip()
49
+ return container_id
50
+
51
+ def shutdown(self, container_id: str) -> None:
52
+ stop_container(self.runtime, container_id)
53
+ remove_container(self.runtime, container_id)
54
+
55
+ @property
56
+ def endpoint_url(self) -> str:
57
+ return f"http://127.0.0.1:{LOCAL_PORT}/v1"
File without changes
@@ -0,0 +1,105 @@
1
+ import os
2
+ import subprocess
3
+
4
+
5
+ class HardwareProfile:
6
+ def __init__(
7
+ self,
8
+ ram_gb: float,
9
+ cpu_cores: int,
10
+ has_nvidia_gpu: bool = False,
11
+ gpu_vram_gb: list[float] | None = None,
12
+ has_amd_gpu: bool = False,
13
+ ):
14
+ self.ram_gb = ram_gb
15
+ self.cpu_cores = cpu_cores
16
+ self.has_nvidia_gpu = has_nvidia_gpu
17
+ self.gpu_vram_gb = gpu_vram_gb or []
18
+ self.has_amd_gpu = has_amd_gpu
19
+
20
+ @property
21
+ def total_gpu_vram_gb(self) -> float:
22
+ return sum(self.gpu_vram_gb)
23
+
24
+ def __repr__(self) -> str:
25
+ return (
26
+ f"HardwareProfile(ram={self.ram_gb}GB, cpu={self.cpu_cores} cores, "
27
+ f"nvidia={self.has_nvidia_gpu}, vram={self.gpu_vram_gb}, "
28
+ f"amd={self.has_amd_gpu})"
29
+ )
30
+
31
+
32
+ def _read_meminfo() -> float:
33
+ try:
34
+ with open("/proc/meminfo") as f:
35
+ for line in f:
36
+ if line.startswith("MemTotal:"):
37
+ kb = int(line.split()[1])
38
+ return round(kb / 1024 / 1024, 1)
39
+ except FileNotFoundError:
40
+ pass
41
+ try:
42
+ result = subprocess.run(
43
+ ["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, timeout=5
44
+ )
45
+ if result.returncode == 0:
46
+ return round(int(result.stdout.strip()) / 1024**3, 1)
47
+ except (FileNotFoundError, subprocess.TimeoutExpired):
48
+ pass
49
+ return 16.0
50
+
51
+
52
+ def _read_cpu_cores() -> int:
53
+ try:
54
+ return os.cpu_count() or 4
55
+ except NotImplementedError:
56
+ return 4
57
+
58
+
59
+ def _detect_nvidia_gpu() -> tuple[bool, list[float]]:
60
+ try:
61
+ result = subprocess.run(
62
+ [
63
+ "nvidia-smi",
64
+ "--query-gpu=memory.total",
65
+ "--format=csv,noheader,nounits",
66
+ ],
67
+ capture_output=True,
68
+ text=True,
69
+ timeout=10,
70
+ )
71
+ if result.returncode == 0:
72
+ vrams = []
73
+ for line in result.stdout.strip().splitlines():
74
+ line = line.strip()
75
+ if line:
76
+ vrams.append(round(int(line) / 1024, 1))
77
+ return (len(vrams) > 0, vrams)
78
+ except (FileNotFoundError, subprocess.TimeoutExpired, ValueError):
79
+ pass
80
+ return (False, [])
81
+
82
+
83
+ def _detect_amd_gpu() -> bool:
84
+ try:
85
+ result = subprocess.run(
86
+ ["rocm-smi"], capture_output=True, text=True, timeout=10
87
+ )
88
+ return result.returncode == 0
89
+ except (FileNotFoundError, subprocess.TimeoutExpired):
90
+ pass
91
+ return False
92
+
93
+
94
+ def detect() -> HardwareProfile:
95
+ ram_gb = _read_meminfo()
96
+ cpu_cores = _read_cpu_cores()
97
+ has_nvidia, gpu_vrams = _detect_nvidia_gpu()
98
+ has_amd = _detect_amd_gpu() if not has_nvidia else False
99
+ return HardwareProfile(
100
+ ram_gb=ram_gb,
101
+ cpu_cores=cpu_cores,
102
+ has_nvidia_gpu=has_nvidia,
103
+ gpu_vram_gb=gpu_vrams,
104
+ has_amd_gpu=has_amd,
105
+ )
File without changes
@@ -0,0 +1,68 @@
1
+ from typing import Any
2
+
3
+ from relaylm.hardware.detector import HardwareProfile
4
+
5
+ # (name, min_ram_gb, min_vram_gb)
6
+ SMALL_MODELS: list[tuple[str, float, float | None]] = [
7
+ ("Qwen/Qwen3-0.6B", 2.0, 1.0),
8
+ ("Qwen/Qwen3-1.5B", 4.0, 2.0),
9
+ ("gemma-3-1b-it-Q4_K_M", 2.0, 1.0),
10
+ ]
11
+
12
+ MEDIUM_MODELS: list[tuple[str, float, float | None]] = [
13
+ ("Qwen/Qwen3-4B", 8.0, 4.0),
14
+ ("mistral-7b-v0.3", 14.0, 4.0),
15
+ ("llama-3.1-8b", 16.0, 5.0),
16
+ ]
17
+
18
+ LARGE_MODELS: list[tuple[str, float, float | None]] = [
19
+ ("Qwen/Qwen3-14B", 28.0, 8.0),
20
+ ("codellama-13b", 26.0, 7.0),
21
+ ("mixtral-8x7b", 48.0, 16.0),
22
+ ]
23
+
24
+
25
+ def _fits_in_ram(model: tuple[str, float, float | None], ram_gb: float) -> bool:
26
+ return model[1] <= ram_gb
27
+
28
+
29
+ def _fits_in_vram(model: tuple[str, float, float | None], vram_gb: float) -> bool:
30
+ vram_needed = model[2]
31
+ return vram_needed is None or vram_needed <= vram_gb
32
+
33
+
34
+ def select_models(
35
+ hardware: HardwareProfile, max_models: int = 2
36
+ ) -> list[dict[str, Any]]:
37
+ models: list[tuple[str, float, float | None]] = []
38
+
39
+ if hardware.gpu_vram_gb:
40
+ vram = max(hardware.gpu_vram_gb)
41
+ candidates = LARGE_MODELS + MEDIUM_MODELS + SMALL_MODELS
42
+ for m in candidates:
43
+ if _fits_in_vram(m, vram) and _fits_in_ram(m, hardware.ram_gb):
44
+ models.append(m)
45
+ else:
46
+ candidates = SMALL_MODELS + MEDIUM_MODELS + LARGE_MODELS
47
+ for m in candidates:
48
+ if _fits_in_ram(m, hardware.ram_gb):
49
+ models.append(m)
50
+
51
+ if not models:
52
+ models = SMALL_MODELS[:1]
53
+
54
+ result: list[dict[str, Any]] = []
55
+ for name, _, _ in models[:max_models]:
56
+ result.append(
57
+ {"name": name, "source": "huggingface", "gpu_index": None, "args": {}}
58
+ )
59
+ return result
60
+
61
+
62
+ def validate_models(model_ids: list[str]) -> list[str]:
63
+ invalid: list[str] = []
64
+ for model_id in model_ids:
65
+ model_id = model_id.strip()
66
+ if not model_id or "/" not in model_id:
67
+ invalid.append(model_id)
68
+ return invalid
@@ -0,0 +1,89 @@
1
+ from typing import Any
2
+
3
+ try:
4
+ from huggingface_hub import HfApi
5
+
6
+ _api: HfApi | None = HfApi()
7
+ except ImportError:
8
+ _api = None
9
+
10
+
11
+ def query_available_models(
12
+ task: str = "text-generation",
13
+ library: str | None = "vllm",
14
+ limit: int = 20,
15
+ ) -> list[dict[str, Any]]:
16
+ if _api is None:
17
+ return _fallback_model_list()
18
+
19
+ try:
20
+ models = _api.list_models(
21
+ task=task,
22
+ library=library,
23
+ sort="downloads",
24
+ direction=-1,
25
+ limit=limit,
26
+ )
27
+ result = []
28
+ for m in models:
29
+ result.append(
30
+ {
31
+ "id": m.id,
32
+ "pipeline_tag": m.pipeline_tag,
33
+ "downloads": getattr(m, "downloads", 0),
34
+ "library": library,
35
+ }
36
+ )
37
+ return result
38
+ except Exception:
39
+ return _fallback_model_list()
40
+
41
+
42
+ def _fallback_model_list() -> list[dict[str, Any]]:
43
+ return [
44
+ {
45
+ "id": "Qwen/Qwen3-0.6B",
46
+ "pipeline_tag": "text-generation",
47
+ "downloads": 0,
48
+ "library": "vllm",
49
+ },
50
+ {
51
+ "id": "Qwen/Qwen3-1.5B",
52
+ "pipeline_tag": "text-generation",
53
+ "downloads": 0,
54
+ "library": "vllm",
55
+ },
56
+ {
57
+ "id": "Qwen/Qwen3-4B",
58
+ "pipeline_tag": "text-generation",
59
+ "downloads": 0,
60
+ "library": "vllm",
61
+ },
62
+ {
63
+ "id": "mistralai/Mistral-7B-Instruct-v0.3",
64
+ "pipeline_tag": "text-generation",
65
+ "downloads": 0,
66
+ "library": "vllm",
67
+ },
68
+ {
69
+ "id": "meta-llama/Llama-3.1-8B",
70
+ "pipeline_tag": "text-generation",
71
+ "downloads": 0,
72
+ "library": "vllm",
73
+ },
74
+ ]
75
+
76
+
77
+ def get_model_info(model_id: str) -> dict[str, Any] | None:
78
+ if _api is None:
79
+ return None
80
+ try:
81
+ info = _api.model_info(model_id)
82
+ return {
83
+ "id": info.id,
84
+ "pipeline_tag": info.pipeline_tag,
85
+ "disabled": getattr(info, "disabled", False),
86
+ "library": getattr(info, "library_name", None),
87
+ }
88
+ except Exception:
89
+ return None
File without changes
@@ -0,0 +1,61 @@
1
+ import os
2
+ import stat
3
+ from pathlib import Path
4
+
5
+ try:
6
+ import keyring as _keyring_module
7
+
8
+ _has_keyring = True
9
+ except ImportError:
10
+ _keyring_module = None # type: ignore[assignment]
11
+ _has_keyring = False
12
+
13
+ KEYCHAIN_FALLBACK_DIR = Path.home() / ".config" / "relaylm" / "secrets"
14
+
15
+
16
+ def _ensure_fallback_dir() -> None:
17
+ KEYCHAIN_FALLBACK_DIR.mkdir(parents=True, exist_ok=True)
18
+ os.chmod(KEYCHAIN_FALLBACK_DIR, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
19
+
20
+
21
+ def store_key(service: str, key: str) -> None:
22
+ if _keyring_module is not None:
23
+ try:
24
+ _keyring_module.set_password(service, "api_key", key)
25
+ return
26
+ except Exception:
27
+ pass
28
+ _ensure_fallback_dir()
29
+ key_path = KEYCHAIN_FALLBACK_DIR / service
30
+ key_path.write_text(key)
31
+ os.chmod(key_path, stat.S_IRUSR | stat.S_IWUSR)
32
+ print(
33
+ f"Warning: API key stored in plaintext at {key_path}. "
34
+ f"Install 'keyring' for secure system keychain storage.",
35
+ file=__import__("sys").stderr,
36
+ )
37
+
38
+
39
+ def get_key(service: str) -> str | None:
40
+ if _keyring_module is not None:
41
+ try:
42
+ result = _keyring_module.get_password(service, "api_key")
43
+ if result is not None:
44
+ return result
45
+ except Exception:
46
+ pass
47
+ key_path = KEYCHAIN_FALLBACK_DIR / service
48
+ if key_path.exists():
49
+ return key_path.read_text().strip()
50
+ return None
51
+
52
+
53
+ def delete_key(service: str) -> None:
54
+ if _keyring_module is not None:
55
+ try:
56
+ _keyring_module.delete_password(service, "api_key")
57
+ except Exception:
58
+ pass
59
+ key_path = KEYCHAIN_FALLBACK_DIR / service
60
+ if key_path.exists():
61
+ key_path.unlink()
@@ -0,0 +1,82 @@
1
+ from typing import Any
2
+
3
+ from relaylm.config.backup import create_backup
4
+ from relaylm.config.loader import load_config, save_config
5
+ from relaylm.providers.keychain import delete_key, get_key, store_key
6
+
7
+ SUPPORTED_PROVIDERS = ("anthropic", "openai")
8
+ DEFAULT_URLS = {
9
+ "anthropic": "https://api.anthropic.com/v1",
10
+ "openai": "https://api.openai.com/v1",
11
+ }
12
+
13
+
14
+ class ProviderManager:
15
+ def __init__(self) -> None:
16
+ self.config = load_config()
17
+
18
+ def list_providers(self) -> list[dict[str, Any]]:
19
+ providers = self.config.get("providers", {})
20
+ result: list[dict[str, Any]] = []
21
+ for name, cfg in providers.items():
22
+ has_key = (
23
+ get_key(cfg.get("keychain_service", f"relaylm-{name}")) is not None
24
+ )
25
+ result.append(
26
+ {
27
+ "name": name,
28
+ "enabled": cfg.get("enabled", False),
29
+ "base_url": cfg.get("base_url", ""),
30
+ "has_key": has_key,
31
+ }
32
+ )
33
+ return result
34
+
35
+ def add_provider(
36
+ self,
37
+ name: str,
38
+ api_key: str,
39
+ base_url: str | None = None,
40
+ ) -> dict[str, str]:
41
+ if name not in SUPPORTED_PROVIDERS:
42
+ raise ValueError(
43
+ f"Unsupported provider: {name}. Supported: {SUPPORTED_PROVIDERS}"
44
+ )
45
+
46
+ create_backup()
47
+
48
+ keychain_service = f"relaylm-{name}"
49
+ store_key(keychain_service, api_key)
50
+
51
+ providers = self.config.setdefault("providers", {})
52
+ providers[name] = {
53
+ "enabled": True,
54
+ "base_url": base_url or DEFAULT_URLS[name],
55
+ "keychain_service": keychain_service,
56
+ }
57
+
58
+ fallback = self.config.setdefault(
59
+ "fallback", {"order": ["local"], "timeout_seconds": 30}
60
+ )
61
+ if name not in fallback.get("order", []):
62
+ fallback.setdefault("order", ["local"]).append(name)
63
+
64
+ save_config(self.config)
65
+ return {"name": name, "status": "configured"}
66
+
67
+ def remove_provider(self, name: str) -> dict[str, str]:
68
+ if name not in SUPPORTED_PROVIDERS:
69
+ raise ValueError(f"Unsupported provider: {name}")
70
+
71
+ create_backup()
72
+ delete_key(f"relaylm-{name}")
73
+
74
+ providers = self.config.get("providers", {})
75
+ providers.pop(name, None)
76
+ fallback = self.config.get("fallback", {})
77
+ order = fallback.get("order", [])
78
+ if name in order:
79
+ order.remove(name)
80
+
81
+ save_config(self.config)
82
+ return {"name": name, "status": "removed"}
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.4
2
+ Name: relaylm
3
+ Version: 0.1.0
4
+ Summary: Single-command AI router environment bootstrap
5
+ Author: RelayLM Contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/anomalyco/relaylm
8
+ Project-URL: Repository, https://github.com/anomalyco/relaylm
9
+ Project-URL: Issues, https://github.com/anomalyco/relaylm/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Topic :: System :: Distributed Computing
19
+ Requires-Python: >=3.11
20
+ License-File: LICENSE
21
+ Requires-Dist: typer>=0.12
22
+ Requires-Dist: pyyaml>=6.0
23
+ Requires-Dist: keyring>=25.0
24
+ Requires-Dist: huggingface-hub>=0.24
25
+ Requires-Dist: pydantic>=2.0
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8.0; extra == "dev"
28
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
29
+ Requires-Dist: ruff>=0.5; extra == "dev"
30
+ Requires-Dist: mypy>=1.10; extra == "dev"
31
+ Dynamic: license-file
@@ -0,0 +1,26 @@
1
+ relaylm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ relaylm/__main__.py,sha256=UWwe8JFv0lX9LythleOmqVv0i1K6ByUVp-uqEIsmQ0s,39
3
+ relaylm/agents/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ relaylm/agents/detector.py,sha256=J6zJK6qZkIsjty17xGzn0zBs0aqgdhzSknfka2Iwwbs,2463
5
+ relaylm/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ relaylm/cli/app.py,sha256=GTWRiwPUf_CzyMCCCr3Ia2D-NnsyZhd_vRsvzRBnLyI,7752
7
+ relaylm/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ relaylm/config/backup.py,sha256=_Rpanet1_Z0aPq8_NbQ2hZYtrCVDi0xeqMpjWU_WBhs,1134
9
+ relaylm/config/loader.py,sha256=mQ3FodWwtmS52bq3RwqxXr8Cc-aYNxXEKfunYqEttmE,1451
10
+ relaylm/container/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ relaylm/container/runtime.py,sha256=fVxFMP1KC-zbyvXvhoAbUA8582rBrxH3TNWJv-65G_4,2517
12
+ relaylm/container/vllm.py,sha256=8ck-Wskw4UjHoy_f50bfsJTLLWhQI8jhYk5sjJQZEY4,1717
13
+ relaylm/hardware/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ relaylm/hardware/detector.py,sha256=9VrP4sTZv5YZrmT6h28eBop_EfbXXzcudywEJxqogdY,2950
15
+ relaylm/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ relaylm/models/selector.py,sha256=r99peKiK_FNJgC_4pzsV89TwUYOcM6RVAbBxTTsMpfI,2028
17
+ relaylm/models/source.py,sha256=EKuO5LhvU4EiLIoyCHfyxjJBiusej69i5He7OmYrwkw,2252
18
+ relaylm/providers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ relaylm/providers/keychain.py,sha256=CeUmKrL7gdgh1Qm2Khoibmx0SzvZ6wCgMt9w3Sq7XQo,1733
20
+ relaylm/providers/manager.py,sha256=cXPfmkpPKhR1vS7BT85holN_3fMbAHNqZDo-JL70ViA,2594
21
+ relaylm-0.1.0.dist-info/licenses/LICENSE,sha256=o8k7RqaGh2XmFjLBPwkqqRmP4JIB71DRSX0lWd_TP7k,1077
22
+ relaylm-0.1.0.dist-info/METADATA,sha256=GgmkU55-Fm7Zr7iAbczT6EDJr5nJx9b7dLSJ62KWjt8,1190
23
+ relaylm-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
24
+ relaylm-0.1.0.dist-info/entry_points.txt,sha256=gteXI4W4-lQe29JeWvFbJ5zw-NQSmQAs0Fzg62Zbqr4,48
25
+ relaylm-0.1.0.dist-info/top_level.txt,sha256=dn30V74S4h27zrQgrZIr1BgDZu6M_DXCINRU0Y5lRHI,8
26
+ relaylm-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ relaylm = relaylm.cli.app:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RelayLM Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ relaylm