llm-lab-runtime 0.2.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.
@@ -0,0 +1,210 @@
1
+ from collections.abc import Mapping
2
+ from dataclasses import dataclass
3
+ from datetime import datetime
4
+ from enum import StrEnum
5
+ from pathlib import Path
6
+ from typing import Annotated, Literal, Self, assert_never
7
+
8
+ import pycountry
9
+ from pydantic import BaseModel, ConfigDict, Field, PositiveFloat, PositiveInt, WithJsonSchema, model_validator
10
+ from pydantic_extra_types.country import CountryAlpha2
11
+
12
+ from llm_lab.keyring_settings import SecretName
13
+
14
+
15
+ class PlacementKind(StrEnum):
16
+ resources = "resources"
17
+ offer = "offer"
18
+
19
+
20
+ class JobCondition(StrEnum):
21
+ pending = "pending"
22
+ running = "running"
23
+ succeeded = "succeeded"
24
+ failed = "failed"
25
+ aborted = "aborted"
26
+
27
+
28
+ type JobName = Annotated[str, Field(pattern=r"^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$")]
29
+ type EnvironmentName = Annotated[str, Field(pattern=r"^[A-Za-z_][A-Za-z0-9_]*$")]
30
+ type CountryCode = Annotated[
31
+ CountryAlpha2,
32
+ WithJsonSchema({"type": "string", "enum": sorted(country.alpha_2 for country in pycountry.countries)}),
33
+ ]
34
+ type CountryCodes = Annotated[tuple[CountryCode, ...], Field(min_length=1)]
35
+
36
+
37
+ class IncludedCountries(BaseModel):
38
+ model_config = ConfigDict(frozen=True, extra="forbid")
39
+
40
+ include: CountryCodes = Field(description="Countries where the host must be, as ISO 3166-1 alpha-2 codes.")
41
+
42
+
43
+ class ExcludedCountries(BaseModel):
44
+ model_config = ConfigDict(frozen=True, extra="forbid")
45
+
46
+ exclude: CountryCodes = Field(description="Countries where the host must not be, as ISO 3166-1 alpha-2 codes.")
47
+
48
+
49
+ class ResourceRequest(BaseModel):
50
+ model_config = ConfigDict(frozen=True, extra="forbid")
51
+
52
+ kind: Literal[PlacementKind.resources]
53
+ gpu_name: Annotated[str, Field(min_length=1)]
54
+ gpu_count: PositiveInt
55
+ max_dollars_per_hour: PositiveFloat = Field(
56
+ description="Ceiling on the total hourly price, which is the compute price plus the storage price for disk_gb."
57
+ )
58
+ max_compute_dollars_per_hour: PositiveFloat | None = Field(
59
+ default=None, description="Ceiling on the hourly price of the machine without storage."
60
+ )
61
+ max_storage_dollars_per_gb_month: PositiveFloat | None = Field(
62
+ default=None, description="Ceiling on the storage price in dollars per GB per month."
63
+ )
64
+ max_download_dollars_per_gb: PositiveFloat | None = Field(
65
+ default=None,
66
+ description="Ceiling on the price of internet download traffic, which Vast.ai bills on top of the hourly price.",
67
+ )
68
+ max_upload_dollars_per_gb: PositiveFloat | None = Field(
69
+ default=None,
70
+ description="Ceiling on the price of internet upload traffic, which Vast.ai bills on top of the hourly price.",
71
+ )
72
+ countries: IncludedCountries | ExcludedCountries | None = Field(
73
+ default=None, description="Countries to include or to exclude. Without it, a host can be in any country."
74
+ )
75
+ datacenter_only: bool = Field(default=False, description="Rent only hosts that Vast.ai lists as datacenters.")
76
+ min_duration_hours: PositiveFloat | None = Field(
77
+ default=None, description="Minimum time in hours that the host must stay available for rent."
78
+ )
79
+ min_cuda: PositiveFloat = Field(
80
+ default=13.0, description="Minimum CUDA version that the driver of the host must support."
81
+ )
82
+
83
+
84
+ class ExplicitOffer(BaseModel):
85
+ model_config = ConfigDict(frozen=True, extra="forbid")
86
+
87
+ kind: Literal[PlacementKind.offer]
88
+ offer_id: int
89
+
90
+
91
+ class JobSpec(BaseModel):
92
+ model_config = ConfigDict(frozen=True, extra="forbid")
93
+
94
+ name: JobName
95
+ image: Annotated[str, Field(min_length=1)]
96
+ command: Annotated[tuple[str, ...], Field(min_length=1)]
97
+ project: Path | None = Field(
98
+ default=None,
99
+ description="Directory of the Python project that holds the code of the job. A relative path starts at the "
100
+ "directory of the manifest file. llm-lab builds a wheel of the project, copies it to the instance, and runs "
101
+ "the command there with `uv run`. Without it, the command runs as written and the image must hold all code.",
102
+ )
103
+ environment: Mapping[EnvironmentName, str] = Field(default_factory=dict)
104
+ secret_environment: tuple[SecretName, ...] = ()
105
+ disk_gb: PositiveFloat
106
+ ttl_seconds_after_finished: PositiveInt
107
+ placement: Annotated[ResourceRequest | ExplicitOffer, Field(discriminator="kind")]
108
+ artifacts_directory: Annotated[str, Field(pattern=r"^/")] | None = None
109
+
110
+ @model_validator(mode="after")
111
+ def reject_names_in_both_environments(self) -> Self:
112
+ repeated = sorted(set(self.environment) & set(self.secret_environment))
113
+ if repeated:
114
+ raise ValueError(f"names {repeated!r} are in environment and in secret_environment")
115
+ return self
116
+
117
+
118
+ class Pending(BaseModel):
119
+ model_config = ConfigDict(frozen=True, extra="forbid")
120
+
121
+ condition: Literal[JobCondition.pending] = JobCondition.pending
122
+ submitted_at: datetime
123
+
124
+
125
+ class Running(BaseModel):
126
+ model_config = ConfigDict(frozen=True, extra="forbid")
127
+
128
+ condition: Literal[JobCondition.running] = JobCondition.running
129
+ submitted_at: datetime
130
+ instance_id: int
131
+
132
+
133
+ class Succeeded(BaseModel):
134
+ model_config = ConfigDict(frozen=True, extra="forbid")
135
+
136
+ condition: Literal[JobCondition.succeeded] = JobCondition.succeeded
137
+ submitted_at: datetime
138
+ finished_at: datetime
139
+ instance_id: int
140
+
141
+
142
+ class Failed(BaseModel):
143
+ model_config = ConfigDict(frozen=True, extra="forbid")
144
+
145
+ condition: Literal[JobCondition.failed] = JobCondition.failed
146
+ submitted_at: datetime
147
+ finished_at: datetime
148
+ instance_id: int
149
+ exit_code: int
150
+
151
+
152
+ class Aborted(BaseModel):
153
+ model_config = ConfigDict(frozen=True, extra="forbid")
154
+
155
+ condition: Literal[JobCondition.aborted] = JobCondition.aborted
156
+ submitted_at: datetime
157
+ finished_at: datetime
158
+ reason: str
159
+
160
+
161
+ class JobRecord(BaseModel):
162
+ model_config = ConfigDict(frozen=True, extra="forbid")
163
+
164
+ spec: JobSpec
165
+ status: Annotated[Pending | Running | Succeeded | Failed | Aborted, Field(discriminator="condition")]
166
+ code_digest: str | None = Field(default=None, description="SHA-256 digest of the wheel that the job received.")
167
+
168
+
169
+ @dataclass(frozen=True)
170
+ class JobCode:
171
+ wheel: Path
172
+ digest: str
173
+
174
+
175
+ @dataclass(frozen=True)
176
+ class Active:
177
+ pass
178
+
179
+
180
+ @dataclass(frozen=True)
181
+ class Completed:
182
+ exit_code: int
183
+
184
+
185
+ @dataclass(frozen=True)
186
+ class Halted:
187
+ instance_state: str
188
+
189
+
190
+ def conclude(running: Running, finished_at: datetime, outcome: Completed | Halted) -> Succeeded | Failed | Aborted:
191
+ match outcome:
192
+ case Completed(exit_code=0):
193
+ return Succeeded(
194
+ submitted_at=running.submitted_at, finished_at=finished_at, instance_id=running.instance_id
195
+ )
196
+ case Completed(exit_code=exit_code):
197
+ return Failed(
198
+ submitted_at=running.submitted_at,
199
+ finished_at=finished_at,
200
+ instance_id=running.instance_id,
201
+ exit_code=exit_code,
202
+ )
203
+ case Halted(instance_state=instance_state):
204
+ return Aborted(
205
+ submitted_at=running.submitted_at,
206
+ finished_at=finished_at,
207
+ reason=f"instance {running.instance_id} became {instance_state} before the command reported an exit code",
208
+ )
209
+ case _:
210
+ assert_never(outcome)
llm_lab/jobs/tables.py ADDED
@@ -0,0 +1,26 @@
1
+ from datetime import datetime
2
+
3
+ from sqlalchemy import Index, Select, func, select
4
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
5
+
6
+
7
+ class Base(DeclarativeBase):
8
+ pass
9
+
10
+
11
+ class JobTransitionRow(Base):
12
+ __tablename__ = "job_transitions"
13
+ __table_args__ = (Index("job_transitions_by_name", "name", "sequence"), {"sqlite_autoincrement": True})
14
+
15
+ sequence: Mapped[int] = mapped_column(primary_key=True)
16
+ name: Mapped[str] = mapped_column()
17
+ condition: Mapped[str] = mapped_column()
18
+ recorded_at: Mapped[datetime] = mapped_column(server_default=func.now())
19
+ record: Mapped[str] = mapped_column()
20
+
21
+
22
+ def select_latest_transitions() -> Select[JobTransitionRow]:
23
+ latest_sequences = select(func.max(JobTransitionRow.sequence)).group_by(JobTransitionRow.name)
24
+ return (
25
+ select(JobTransitionRow).where(JobTransitionRow.sequence.in_(latest_sequences)).order_by(JobTransitionRow.name)
26
+ )
llm_lab/jobs/vast.py ADDED
@@ -0,0 +1,344 @@
1
+ import base64
2
+ import json
3
+ import re
4
+ import shlex
5
+ from collections.abc import Callable, Mapping, Sequence
6
+ from pathlib import Path
7
+ from typing import assert_never
8
+
9
+ import httpx
10
+ from pydantic import BaseModel, Field, SecretStr
11
+
12
+ from llm_lab.errors import CommandError
13
+ from llm_lab.jobs.access import InstanceAccess, SshEndpoint
14
+ from llm_lab.jobs.protocol import (
15
+ Active,
16
+ Completed,
17
+ ExcludedCountries,
18
+ ExplicitOffer,
19
+ Halted,
20
+ IncludedCountries,
21
+ JobSpec,
22
+ ResourceRequest,
23
+ )
24
+ from llm_lab.keyring_settings import SecretName
25
+ from llm_lab.settings import Settings
26
+
27
+
28
+ class Offer(BaseModel):
29
+ id: int
30
+ dph_total: float
31
+
32
+
33
+ class OfferPage(BaseModel):
34
+ offers: list[Offer]
35
+
36
+
37
+ class CreatedInstance(BaseModel):
38
+ new_contract: int
39
+
40
+
41
+ class InstanceView(BaseModel):
42
+ actual_status: str | None
43
+
44
+
45
+ class InstanceEnvelope(BaseModel):
46
+ instances: InstanceView | None
47
+
48
+
49
+ class PortBinding(BaseModel):
50
+ host_port: int = Field(alias="HostPort")
51
+
52
+
53
+ class InstanceAddress(BaseModel):
54
+ public_ipaddr: str | None = None
55
+ ports: dict[str, list[PortBinding]] | None = None
56
+
57
+
58
+ class AddressEnvelope(BaseModel):
59
+ instances: InstanceAddress
60
+
61
+
62
+ class InstanceIdentity(BaseModel):
63
+ id: int
64
+
65
+
66
+ class InstancePage(BaseModel):
67
+ instances: list[InstanceIdentity] | None
68
+ next_token: str | None = None
69
+
70
+
71
+ class RequestedLog(BaseModel):
72
+ result_url: str
73
+
74
+
75
+ def label_job(job_name: str) -> str:
76
+ return f"llm-lab-job-{job_name}"
77
+
78
+
79
+ def build_offer_query(request: ResourceRequest, disk_gb: float, limit: int) -> dict[str, object]:
80
+ ceilings = {
81
+ "dph_base": request.max_compute_dollars_per_hour,
82
+ "storage_cost": request.max_storage_dollars_per_gb_month,
83
+ "inet_down_cost": request.max_download_dollars_per_gb,
84
+ "inet_up_cost": request.max_upload_dollars_per_gb,
85
+ }
86
+ match request.countries:
87
+ case IncludedCountries(include=codes):
88
+ location = {"geolocation": {"in": list(codes)}}
89
+ case ExcludedCountries(exclude=codes):
90
+ location = {"geolocation": {"notin": list(codes)}}
91
+ case None:
92
+ location = {}
93
+ case _:
94
+ assert_never(request.countries)
95
+ return {
96
+ **{field: {"lte": ceiling} for field, ceiling in ceilings.items() if ceiling is not None},
97
+ **location,
98
+ **({"datacenter": {"eq": True}} if request.datacenter_only else {}),
99
+ **({} if request.min_duration_hours is None else {"duration": {"gte": request.min_duration_hours * 3600}}),
100
+ "cuda_max_good": {"gte": request.min_cuda},
101
+ "gpu_name": {"eq": request.gpu_name},
102
+ "num_gpus": {"eq": request.gpu_count},
103
+ "disk_space": {"gte": disk_gb},
104
+ "dph_total": {"lte": request.max_dollars_per_hour},
105
+ "verified": {"eq": True},
106
+ "external": {"eq": False},
107
+ "rentable": {"eq": True},
108
+ "rented": {"eq": False},
109
+ "direct_port_count": {"gte": 1},
110
+ "allocated_storage": disk_gb,
111
+ "type": "ondemand",
112
+ "order": [["dph_total", "asc"]],
113
+ "limit": limit,
114
+ }
115
+
116
+
117
+ def build_job_command(spec: JobSpec, settings: Settings) -> str:
118
+ match spec.project:
119
+ case None:
120
+ return shlex.join(spec.command)
121
+ case Path():
122
+ directory = shlex.quote(settings.job_code_directory.rstrip("/"))
123
+ wait = f"until ls {directory}/*.whl >/dev/null 2>&1; do sleep 1; done"
124
+ return " && ".join(
125
+ [
126
+ f"mkdir -p {directory}",
127
+ f"timeout {settings.job_code_timeout_seconds} sh -c {shlex.quote(wait)}",
128
+ f"uv run --no-project --with {directory}/*.whl -- {shlex.join(spec.command)}",
129
+ ]
130
+ )
131
+ case _:
132
+ assert_never(spec.project)
133
+
134
+
135
+ def build_instance_request(
136
+ spec: JobSpec, secrets: Mapping[SecretName, SecretStr], access: InstanceAccess, settings: Settings
137
+ ) -> dict[str, object]:
138
+ # Vast.ai overwrites /root/.ssh/authorized_keys after the container starts.
139
+ script = "\n".join(
140
+ [
141
+ "if command -v sshd >/dev/null 2>&1; then",
142
+ "mkdir -p -m 700 /run/sshd /root/.ssh",
143
+ "mkdir -p /etc/profile.d",
144
+ "printf '%s\\n' \"$LLM_LAB_SSH_AUTHORIZED_KEY\" > /run/sshd/llm-lab-authorized-keys",
145
+ "(umask 077 && printf '%s' \"$LLM_LAB_SSH_HOST_KEY\" | base64 -d > /run/sshd/llm-lab-host-key)",
146
+ 'printf \'export PATH="%s"\\n\' "$PATH" > /etc/profile.d/llm-lab-path.sh',
147
+ f'"$(command -v sshd)" -p {settings.vast_ssh_port} -h /run/sshd/llm-lab-host-key '
148
+ "-o 'AuthorizedKeysFile=/run/sshd/llm-lab-authorized-keys .ssh/authorized_keys' "
149
+ "-o PasswordAuthentication=no -o KbdInteractiveAuthentication=no -o PermitRootLogin=prohibit-password",
150
+ "fi",
151
+ "if [ ! -e /llm-lab-job-done ]; then",
152
+ build_job_command(spec, settings),
153
+ "exit_code=$?",
154
+ "touch /llm-lab-job-done",
155
+ 'echo "llm-lab-job-exit-code=$exit_code"',
156
+ "fi",
157
+ f"sleep {spec.ttl_seconds_after_finished}",
158
+ 'curl -fsS -X DELETE -H "Authorization: Bearer $CONTAINER_API_KEY" '
159
+ f'"{settings.vast_api_url}/v0/instances/$CONTAINER_ID/"',
160
+ ]
161
+ )
162
+ return {
163
+ "client_id": "me",
164
+ "image": spec.image,
165
+ "disk": spec.disk_gb,
166
+ "label": label_job(spec.name),
167
+ "runtype": "args",
168
+ "args": ["sh", "-c", script],
169
+ "env": {
170
+ **spec.environment,
171
+ **{name: secret.get_secret_value() for name, secret in secrets.items()},
172
+ "LLM_LAB_SSH_AUTHORIZED_KEY": access.authorized_key,
173
+ "LLM_LAB_SSH_HOST_KEY": base64.b64encode(access.host_private_key.get_secret_value().encode()).decode(),
174
+ f"-p {settings.vast_ssh_port}:{settings.vast_ssh_port}": "1",
175
+ },
176
+ }
177
+
178
+
179
+ def read_exit_code(log_text: str) -> int | None:
180
+ reported = re.findall(r"llm-lab-job-exit-code=(\d+)", log_text)
181
+ return int(reported[-1]) if reported else None
182
+
183
+
184
+ def classify(actual_status: str | None, exit_code: int | None) -> Active | Completed | Halted:
185
+ if exit_code is not None:
186
+ return Completed(exit_code)
187
+ match actual_status:
188
+ case "exited" | "offline" | "unknown":
189
+ return Halted(actual_status)
190
+ case _:
191
+ return Active()
192
+
193
+
194
+ class VastInstanceProvider:
195
+ def __init__(self, settings: Settings, http: httpx.Client, sleep: Callable[[float], None]) -> None:
196
+ if settings.vast_api_key is None:
197
+ raise CommandError("The Vast.ai API key is not set. Run `llm-lab secrets set VAST_API_KEY`.")
198
+ self.settings = settings
199
+ self.api_key = settings.vast_api_key
200
+ self.http = http
201
+ self.sleep = sleep
202
+
203
+ def find_offers(self, spec: JobSpec) -> Sequence[int]:
204
+ match spec.placement:
205
+ case ExplicitOffer(offer_id=offer_id):
206
+ return [offer_id]
207
+ case ResourceRequest() as request:
208
+ response = self.call_api(
209
+ "POST", "/v0/bundles/", build_offer_query(request, spec.disk_gb, self.settings.vast_offer_limit)
210
+ )
211
+ self.require_success(response)
212
+ offers = OfferPage.model_validate_json(response.content).offers
213
+ return [offer.id for offer in sorted(offers, key=lambda offer: offer.dph_total)]
214
+ case _:
215
+ assert_never(spec.placement)
216
+
217
+ def rent_offer(
218
+ self, offer_id: int, spec: JobSpec, secrets: Mapping[SecretName, SecretStr], access: InstanceAccess
219
+ ) -> int | None:
220
+ response = self.call_api(
221
+ "PUT",
222
+ f"/v0/asks/{offer_id}/",
223
+ build_instance_request(spec, secrets, access, self.settings),
224
+ )
225
+ if response.status_code in {404, 410}:
226
+ return None
227
+ self.require_success(response)
228
+ return CreatedInstance.model_validate_json(response.content).new_contract
229
+
230
+ def observe(self, instance_id: int) -> Active | Completed | Halted:
231
+ response = self.call_api("GET", f"/v0/instances/{instance_id}/", None)
232
+ if response.status_code == 404:
233
+ return Halted("missing")
234
+ self.require_success(response)
235
+ view = InstanceEnvelope.model_validate_json(response.content).instances
236
+ if view is None:
237
+ return Halted("missing")
238
+ match view.actual_status:
239
+ case "running" | "exited" as actual_status:
240
+ requested = self.call_api(
241
+ "PUT",
242
+ f"/v0/instances/request_logs/{instance_id}/",
243
+ {"tail": str(self.settings.vast_log_tail_lines)},
244
+ )
245
+ if actual_status == "exited" and requested.is_client_error:
246
+ return Halted(actual_status)
247
+ self.require_success(requested)
248
+ return classify(actual_status, self.download_reported_exit_code(requested))
249
+ case _:
250
+ return classify(view.actual_status, None)
251
+
252
+ def find_ssh_endpoint(self, instance_id: int) -> SshEndpoint | None:
253
+ response = self.call_api("GET", f"/v0/instances/{instance_id}/", None)
254
+ self.require_success(response)
255
+ address = AddressEnvelope.model_validate_json(response.content).instances
256
+ if address.public_ipaddr is None or address.ports is None:
257
+ return None
258
+ match address.ports.get(f"{self.settings.vast_ssh_port}/tcp", []):
259
+ case [binding, *_]:
260
+ return SshEndpoint(host=address.public_ipaddr, port=binding.host_port)
261
+ case _:
262
+ return None
263
+
264
+ def find_instances(self, job_name: str) -> Sequence[int]:
265
+ params = {
266
+ "select_filters": json.dumps({"label": {"eq": label_job(job_name)}}),
267
+ "order_by": json.dumps([{"col": "id", "dir": "asc"}]),
268
+ "limit": "25",
269
+ }
270
+ found: list[int] = []
271
+ while True:
272
+ response = self.send_with_retries(
273
+ "GET",
274
+ f"{self.settings.vast_api_url}/v1/instances/",
275
+ {500, 502, 503, 504},
276
+ headers=self.authorize(),
277
+ params=params,
278
+ )
279
+ self.require_success(response)
280
+ page = InstancePage.model_validate_json(response.content)
281
+ found.extend(instance.id for instance in page.instances or [])
282
+ if page.next_token is None:
283
+ return found
284
+ params = params | {"after_token": page.next_token}
285
+
286
+ def destroy(self, instance_id: int) -> None:
287
+ response = self.call_api("DELETE", f"/v0/instances/{instance_id}/", {})
288
+ if response.is_success or response.status_code == 404:
289
+ return
290
+ match self.observe(instance_id):
291
+ case Halted(instance_state="missing"):
292
+ return
293
+ case _:
294
+ self.require_success(response)
295
+
296
+ def download_reported_exit_code(self, requested: httpx.Response) -> int | None:
297
+ log = self.send_with_retries(
298
+ "GET", RequestedLog.model_validate_json(requested.content).result_url, {403, 404, 500, 502, 503, 504}
299
+ )
300
+ if log.status_code in {403, 404}:
301
+ return None
302
+ self.require_success(log)
303
+ return read_exit_code(log.text)
304
+
305
+ def authorize(self) -> dict[str, str]:
306
+ return {"Authorization": f"Bearer {self.api_key.get_secret_value()}"}
307
+
308
+ def call_api(self, method: str, path: str, body: object) -> httpx.Response:
309
+ return self.send_with_retries(
310
+ method, f"{self.settings.vast_api_url}{path}", {500, 502, 503, 504}, headers=self.authorize(), json=body
311
+ )
312
+
313
+ def send_with_retries(
314
+ self,
315
+ method: str,
316
+ url: str,
317
+ retried_statuses: set[int],
318
+ *,
319
+ headers: dict[str, str] | None = None,
320
+ params: dict[str, str] | None = None,
321
+ json: object = None,
322
+ ) -> httpx.Response:
323
+ response = self.send(method, url, headers, params, json)
324
+ for attempt in range(1, self.settings.vast_request_attempts):
325
+ if response.status_code != 429 and response.status_code not in retried_statuses:
326
+ break
327
+ self.sleep(self.settings.vast_retry_delay_seconds * attempt)
328
+ response = self.send(method, url, headers, params, json)
329
+ return response
330
+
331
+ def send(
332
+ self, method: str, url: str, headers: dict[str, str] | None, params: dict[str, str] | None, json: object
333
+ ) -> httpx.Response:
334
+ try:
335
+ return self.http.request(method, url, headers=headers, params=params, json=json)
336
+ except httpx.TransportError as error:
337
+ raise CommandError(f"The request to {httpx.URL(url).host} did not complete: {error}") from error
338
+
339
+ def require_success(self, response: httpx.Response) -> None:
340
+ if not response.is_success:
341
+ request = response.request
342
+ raise CommandError(
343
+ f"{request.url.host} returned status {response.status_code} for {request.method} {request.url.path}."
344
+ )
@@ -0,0 +1,50 @@
1
+ from collections.abc import Callable
2
+ from dataclasses import dataclass
3
+ from enum import StrEnum
4
+
5
+ import keyring
6
+ from keyring.errors import NoKeyringError
7
+ from pydantic.fields import FieldInfo
8
+ from pydantic_settings import BaseSettings, PydanticBaseSettingsSource
9
+
10
+
11
+ class SecretName(StrEnum):
12
+ hf_token = "HF_TOKEN"
13
+ vast_api_key = "VAST_API_KEY"
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class KeyringEntry:
18
+ service: str
19
+ username: str
20
+
21
+
22
+ def read_keyring_entry(field: FieldInfo, field_name: str) -> KeyringEntry | None:
23
+ match [item for item in field.metadata if isinstance(item, KeyringEntry)]:
24
+ case []:
25
+ return None
26
+ case [KeyringEntry() as entry]:
27
+ return entry
28
+ case _:
29
+ raise TypeError(f"field {field_name!r} has more than one KeyringEntry annotation")
30
+
31
+
32
+ def read_keyring_password(entry: KeyringEntry) -> str | None:
33
+ try:
34
+ return keyring.get_password(entry.service, entry.username)
35
+ except NoKeyringError:
36
+ return None
37
+
38
+
39
+ class SecretSettingsSource(PydanticBaseSettingsSource):
40
+ def __init__(self, settings_cls: type[BaseSettings], read: Callable[[KeyringEntry], str | None]) -> None:
41
+ super().__init__(settings_cls)
42
+ self.read = read
43
+
44
+ def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[str | None, str, bool]:
45
+ entry = read_keyring_entry(field, field_name)
46
+ return (None if entry is None else self.read(entry)), field_name, False
47
+
48
+ def __call__(self) -> dict[str, object]:
49
+ values = {name: self.get_field_value(field, name)[0] for name, field in self.settings_cls.model_fields.items()}
50
+ return {name: value for name, value in values.items() if value is not None}
File without changes
@@ -0,0 +1,13 @@
1
+ from alembic import context
2
+ from sqlalchemy import Engine
3
+
4
+ from llm_lab.jobs.tables import JobTransitionRow
5
+
6
+ match context.config.attributes.get("engine"):
7
+ case Engine() as engine:
8
+ with engine.connect() as connection:
9
+ context.configure(connection=connection, target_metadata=JobTransitionRow.metadata, render_as_batch=True)
10
+ with context.begin_transaction():
11
+ context.run_migrations()
12
+ case _:
13
+ raise TypeError("the Alembic configuration has no engine attribute")
@@ -0,0 +1,17 @@
1
+ """${message}"""
2
+
3
+ import sqlalchemy as sa
4
+ from alembic import op
5
+ ${imports if imports else ""}
6
+ revision: str = ${repr(up_revision)}
7
+ down_revision: str | None = ${repr(down_revision)}
8
+ branch_labels: str | tuple[str, ...] | None = ${repr(branch_labels)}
9
+ depends_on: str | tuple[str, ...] | None = ${repr(depends_on)}
10
+
11
+
12
+ def upgrade() -> None:
13
+ ${upgrades if upgrades else "pass"}
14
+
15
+
16
+ def downgrade() -> None:
17
+ ${downgrades if downgrades else "pass"}