envloop-cli 2.0.0__py3-none-any.whl → 2.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.
- envloop/cli.py +3 -0
- envloop/cli_errors.py +5 -2
- envloop/http.py +10 -8
- envloop_asset/assets.py +15 -6
- envloop_asset/cli_output.py +2 -2
- envloop_asset/client.py +24 -20
- envloop_asset/direct_checkpoint.py +41 -3
- envloop_asset/direct_publication.py +43 -5
- envloop_asset/direct_storage.py +6 -2
- envloop_asset/recipe_packages.py +2 -2
- envloop_asset/resource_cli.py +7 -17
- envloop_asset/runner_packages.py +27 -4
- envloop_asset/tags.py +20 -0
- envloop_asset/transfer.py +148 -21
- envloop_chat/__init__.py +1 -0
- envloop_chat/cli.py +116 -0
- envloop_chat/client.py +146 -0
- {envloop_cli-2.0.0.dist-info → envloop_cli-2.2.0.dist-info}/METADATA +38 -28
- {envloop_cli-2.0.0.dist-info → envloop_cli-2.2.0.dist-info}/RECORD +26 -23
- envloop_experiment/cli.py +14 -5
- envloop_experiment/client.py +23 -10
- envloop_experiment/http.py +1 -2
- envloop_experiment/job_spec_cli.py +6 -3
- envloop_experiment/named_profile.py +5 -1
- {envloop_cli-2.0.0.dist-info → envloop_cli-2.2.0.dist-info}/WHEEL +0 -0
- {envloop_cli-2.0.0.dist-info → envloop_cli-2.2.0.dist-info}/entry_points.txt +0 -0
envloop_asset/transfer.py
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
"""Project-scoped EL Assets CRUD and verified, resumable transfers."""
|
|
2
2
|
import base64
|
|
3
3
|
import hashlib
|
|
4
|
+
import inspect
|
|
4
5
|
import json
|
|
5
6
|
import os
|
|
6
7
|
import re
|
|
7
8
|
import stat
|
|
9
|
+
import threading
|
|
8
10
|
import time
|
|
9
11
|
from collections.abc import Mapping, Sequence
|
|
12
|
+
from concurrent.futures import Future, ThreadPoolExecutor
|
|
10
13
|
from contextlib import contextmanager
|
|
11
14
|
from dataclasses import dataclass
|
|
12
15
|
from functools import partial
|
|
@@ -177,6 +180,17 @@ class AssetTransfer:
|
|
|
177
180
|
def download_directory(self, uri: str, destination: str | Path, *, split: str | None = None, config: str | None = None,
|
|
178
181
|
content_digest: str | None = None, task_id: str | None = None, task_digest: str | None = None):
|
|
179
182
|
"""Download a complete ANS directory using EnvHub and temporary URLs; `uri` may be an Asset ID."""
|
|
183
|
+
started = time.perf_counter()
|
|
184
|
+
timings: dict[str, Any] = {'queries': [], 'files': [], 'plan_validation_seconds': 0.0}
|
|
185
|
+
managed_timings = os.environ.get('ENVLOOP_DATA_TIMINGS') == '1'
|
|
186
|
+
|
|
187
|
+
def query(operation: str, call: Callable[[], Any]) -> Any:
|
|
188
|
+
before = time.perf_counter()
|
|
189
|
+
try:
|
|
190
|
+
return call()
|
|
191
|
+
finally:
|
|
192
|
+
timings['queries'].append({'operation': operation, 'seconds': time.perf_counter() - before})
|
|
193
|
+
|
|
180
194
|
from envloop._optional import require_asset_dependencies
|
|
181
195
|
|
|
182
196
|
require_asset_dependencies()
|
|
@@ -187,7 +201,7 @@ class AssetTransfer:
|
|
|
187
201
|
'runners':'runner', 'recipes':'recipe'}
|
|
188
202
|
resource = None
|
|
189
203
|
if isinstance(uri, str) and not uri.startswith('envloop://'):
|
|
190
|
-
resource = self.get(uri)
|
|
204
|
+
resource = query('resolve_resource', lambda: self.get(uri))
|
|
191
205
|
ref = resource.get('ref') or resource.get('model_uri')
|
|
192
206
|
if not isinstance(ref, str) or not ref:
|
|
193
207
|
raise ValueError('this Asset resource has no downloadable ANS reference')
|
|
@@ -215,48 +229,161 @@ class AssetTransfer:
|
|
|
215
229
|
raise ValueError('Task download requires paired task_id namespace/name and task_digest sha256:SHA256')
|
|
216
230
|
endpoint = self._path(uri) + '/download'
|
|
217
231
|
parameters = {'split': split, 'config': config, 'content_digest': content_digest, **task_selection}
|
|
218
|
-
plan = self.transport.request('GET', self._query(endpoint, **parameters))
|
|
232
|
+
plan = query('download_plan', lambda: self.transport.request('GET', self._query(endpoint, **parameters)))
|
|
219
233
|
from envhub.ans.client import validate_download_plan
|
|
234
|
+
before_validation = time.perf_counter()
|
|
220
235
|
try:
|
|
221
|
-
validate_download_plan(plan, uri=uri, split=split, content_digest=content_digest,
|
|
236
|
+
manifest, _, _ = validate_download_plan(plan, uri=uri, split=split, content_digest=content_digest,
|
|
222
237
|
**({'config': config} if config is not None else {}), **task_selection)
|
|
223
238
|
except (ANSError, InvalidManifest, ValueError, TypeError, KeyError):
|
|
224
239
|
raise RemoteError('ASSET_INTEGRITY_FAILED', 409) from None
|
|
240
|
+
timings['plan_validation_seconds'] += time.perf_counter() - before_validation
|
|
225
241
|
originals = {entry['url']: entry['path'] for entry in plan.get('files', [])}
|
|
226
242
|
current = {entry['path']: entry['url'] for entry in plan.get('files', [])}
|
|
227
243
|
pins = [{key: entry[key] for key in ('path','size','sha256','mode')} for entry in plan.get('files', [])]
|
|
244
|
+
files = {entry['path']: {'index': index, 'bytes': 0, 'requests': 0,
|
|
245
|
+
'connect_seconds': 0.0, 'read_seconds': 0.0}
|
|
246
|
+
for index, entry in enumerate(plan.get('files', []))}
|
|
247
|
+
sizes = {entry['path']: entry['size'] for entry in manifest['files']}
|
|
248
|
+
renewal_lock = threading.Lock()
|
|
249
|
+
|
|
250
|
+
def open_file(path: str, url: str) -> Any:
|
|
251
|
+
row = files[path]
|
|
252
|
+
row['requests'] += 1
|
|
253
|
+
before = time.perf_counter()
|
|
254
|
+
try:
|
|
255
|
+
return self.transport.open_download(url)
|
|
256
|
+
finally:
|
|
257
|
+
row['connect_seconds'] += time.perf_counter() - before
|
|
228
258
|
|
|
229
|
-
def
|
|
259
|
+
def network_read(url: str):
|
|
230
260
|
path = originals[url]
|
|
261
|
+
with renewal_lock:
|
|
262
|
+
attempted = current[path]
|
|
231
263
|
try:
|
|
232
|
-
stream =
|
|
264
|
+
stream = open_file(path, attempted)
|
|
233
265
|
except RemoteError as error:
|
|
234
266
|
if error.status_code != 403:
|
|
235
267
|
raise
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
or [{key: entry.get(key) for key in ('path','size','sha256','mode')}
|
|
242
|
-
for entry in renewed.get('files', [])] != pins):
|
|
243
|
-
raise RemoteError('ASSET_PIN_CONFLICT', 409)
|
|
244
|
-
# EnvHub validates renewed URLs before any storage request.
|
|
245
|
-
validate_download_plan(renewed, uri=uri, split=split, content_digest=plan['content_digest'],
|
|
246
|
-
**({'config': config} if config is not None else {}), **task_selection)
|
|
247
|
-
current.update({entry['path']: entry['url'] for entry in renewed['files']})
|
|
248
|
-
stream = self.transport.open_download(current[path])
|
|
268
|
+
with renewal_lock:
|
|
269
|
+
if current[path] == attempted:
|
|
270
|
+
renew()
|
|
271
|
+
replacement = current[path]
|
|
272
|
+
stream = open_file(path, replacement)
|
|
249
273
|
with stream:
|
|
250
|
-
while
|
|
274
|
+
while True:
|
|
275
|
+
before = time.perf_counter()
|
|
276
|
+
try:
|
|
277
|
+
chunk = stream.read(1024 * 1024)
|
|
278
|
+
finally:
|
|
279
|
+
files[path]['read_seconds'] += time.perf_counter() - before
|
|
280
|
+
if not chunk:
|
|
281
|
+
break
|
|
282
|
+
files[path]['bytes'] += len(chunk)
|
|
283
|
+
if files[path]['bytes'] > sizes[path]:
|
|
284
|
+
raise RemoteError('ASSET_INTEGRITY_FAILED', 409)
|
|
251
285
|
yield chunk
|
|
252
286
|
|
|
287
|
+
def renew() -> None:
|
|
288
|
+
renewed = query('renew_download_plan', lambda: self.transport.request(
|
|
289
|
+
'GET', self._query(endpoint, **(parameters | {'content_digest': plan['content_digest']}))))
|
|
290
|
+
if (renewed.get('uri') != uri or renewed.get('split') != split
|
|
291
|
+
or renewed.get('config') != config
|
|
292
|
+
or renewed.get('task_id') != task_id or renewed.get('task_digest') != task_digest
|
|
293
|
+
or renewed.get('content_digest') != plan['content_digest']
|
|
294
|
+
or [{key: entry.get(key) for key in ('path','size','sha256','mode')}
|
|
295
|
+
for entry in renewed.get('files', [])] != pins):
|
|
296
|
+
raise RemoteError('ASSET_PIN_CONFLICT', 409)
|
|
297
|
+
# EnvHub validates renewed URLs before any storage request.
|
|
298
|
+
before_validation = time.perf_counter()
|
|
299
|
+
validate_download_plan(renewed, uri=uri, split=split, content_digest=plan['content_digest'],
|
|
300
|
+
**({'config': config} if config is not None else {}), **task_selection)
|
|
301
|
+
timings['plan_validation_seconds'] += time.perf_counter() - before_validation
|
|
302
|
+
current.update({entry['path']: entry['url'] for entry in renewed['files']})
|
|
303
|
+
|
|
304
|
+
# A bounded look-ahead hides connection latency for directory trees of
|
|
305
|
+
# tiny source files. Large files keep the existing streaming path.
|
|
306
|
+
small_paths = [entry['path'] for entry in manifest['files'] if entry['size'] <= 1024 * 1024]
|
|
307
|
+
parallel = len(small_paths) >= 4
|
|
308
|
+
small = iter(small_paths)
|
|
309
|
+
pending: dict[str, Future[bytes]] = {}
|
|
310
|
+
pool = ThreadPoolExecutor(max_workers=4) if parallel else None
|
|
311
|
+
activated = False
|
|
312
|
+
waiting_seconds = 0.0
|
|
313
|
+
|
|
314
|
+
def fetch_small(url: str) -> bytes:
|
|
315
|
+
return b''.join(network_read(url))
|
|
316
|
+
|
|
317
|
+
def schedule() -> None:
|
|
318
|
+
path = next(small, None)
|
|
319
|
+
if path is not None and pool is not None:
|
|
320
|
+
pending[path] = pool.submit(fetch_small, plan['files'][files[path]['index']]['url'])
|
|
321
|
+
|
|
322
|
+
def read(url: str):
|
|
323
|
+
nonlocal activated, waiting_seconds
|
|
324
|
+
path = originals[url]
|
|
325
|
+
if parallel and not activated:
|
|
326
|
+
# Called only after EnvHub has checked the quota, destination
|
|
327
|
+
# and entire plan. No speculative object requests before that.
|
|
328
|
+
activated = True
|
|
329
|
+
for _ in range(4):
|
|
330
|
+
schedule()
|
|
331
|
+
if path in pending:
|
|
332
|
+
before = time.perf_counter()
|
|
333
|
+
try:
|
|
334
|
+
payload = pending.pop(path).result()
|
|
335
|
+
finally:
|
|
336
|
+
waiting_seconds += time.perf_counter() - before
|
|
337
|
+
schedule()
|
|
338
|
+
yield payload
|
|
339
|
+
return
|
|
340
|
+
source = iter(network_read(url))
|
|
341
|
+
while True:
|
|
342
|
+
before = time.perf_counter()
|
|
343
|
+
try:
|
|
344
|
+
chunk = next(source)
|
|
345
|
+
except StopIteration:
|
|
346
|
+
return
|
|
347
|
+
finally:
|
|
348
|
+
waiting_seconds += time.perf_counter() - before
|
|
349
|
+
yield chunk
|
|
350
|
+
|
|
351
|
+
# This reader owns the four bounded look-ahead workers and its wait
|
|
352
|
+
# clock. New Hub versions also parallelize custom readers by default;
|
|
353
|
+
# keep one materialization coordinator. Older Hub readers are serial.
|
|
354
|
+
materialization_options: dict[str, Any] = (
|
|
355
|
+
{'max_workers': 1} if 'max_workers' in inspect.signature(download_directory).parameters else {})
|
|
356
|
+
materialization_options.update({'config': config} if config is not None else {})
|
|
357
|
+
materialization_options.update(task_selection)
|
|
358
|
+
materialize_started = time.perf_counter()
|
|
359
|
+
materialize_cpu_started = time.thread_time()
|
|
360
|
+
query_count = len(timings['queries'])
|
|
361
|
+
validation_before_materialize = timings['plan_validation_seconds']
|
|
253
362
|
try:
|
|
254
363
|
target = download_directory(plan, Path(destination), uri=uri, split=split, content_digest=content_digest, read_url=read,
|
|
255
|
-
**
|
|
364
|
+
**materialization_options)
|
|
256
365
|
except (ANSError, InvalidManifest, ValueError, TypeError, KeyError):
|
|
257
366
|
raise RemoteError('ASSET_INTEGRITY_FAILED', 409) from None
|
|
367
|
+
finally:
|
|
368
|
+
if pool is not None:
|
|
369
|
+
pool.shutdown(wait=True, cancel_futures=True)
|
|
370
|
+
timings['files'] = list(files.values())[:256]
|
|
371
|
+
timings['files_truncated'] = len(files) > 256
|
|
372
|
+
materialize_seconds = time.perf_counter() - materialize_started
|
|
373
|
+
network_seconds = sum(row['connect_seconds'] + row['read_seconds'] for row in files.values())
|
|
374
|
+
renewal_seconds = sum(row['seconds'] for row in timings['queries'][query_count:])
|
|
375
|
+
renewal_validation = timings['plan_validation_seconds'] - validation_before_materialize
|
|
376
|
+
timings['materialize_verify_seconds'] = max(0.0, materialize_seconds - (
|
|
377
|
+
waiting_seconds if parallel else network_seconds + renewal_seconds + renewal_validation))
|
|
378
|
+
timings['materialize_verify_cpu_seconds'] = time.thread_time() - materialize_cpu_started
|
|
379
|
+
timings['network_wait_seconds'] = waiting_seconds
|
|
380
|
+
timings['small_file_workers'] = 4 if parallel else 1
|
|
381
|
+
timings['queries_truncated'] = len(timings['queries']) > 256
|
|
382
|
+
timings['queries'] = timings['queries'][:256]
|
|
383
|
+
timings['total_seconds'] = time.perf_counter() - started
|
|
258
384
|
return {'ref': uri, 'split': split, 'content_digest': plan['content_digest'],
|
|
259
|
-
'directory': str(target), 'verified': True, **({'config': config} if config is not None else {}), **task_selection
|
|
385
|
+
'directory': str(target), 'verified': True, **({'config': config} if config is not None else {}), **task_selection,
|
|
386
|
+
**({'timings': timings} if managed_timings else {})}
|
|
260
387
|
|
|
261
388
|
def create(self, *, type: str, ref: str | None = None, manifest: dict[str, Any] | None = None, files: dict[str, Any] | None = None, model: str | None = None, revision: str | None = None,
|
|
262
389
|
executables: Sequence[str] = (), dry_run: bool = False, idempotency_key: str | None = None, visibility: str | None = None, wait: bool = True,
|
envloop_chat/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Optional Job chat; install envloop-cli[chat] to load the OpenAI SDK."""
|
envloop_chat/cli.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Single-turn and terminal chat; model traffic stays in the optional SDK module."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
from collections.abc import Generator
|
|
6
|
+
from contextlib import closing
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, cast
|
|
9
|
+
|
|
10
|
+
from envloop.http import RemoteError
|
|
11
|
+
from envloop.terminal import safe_text
|
|
12
|
+
|
|
13
|
+
from .client import require_dependencies, validate
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def register(jobs: Any) -> None:
|
|
17
|
+
parser = jobs.add_parser('chat', help='Chat with an Inference Job (install envloop-cli[chat])')
|
|
18
|
+
parser.add_argument('job_id', metavar='JOB_ID')
|
|
19
|
+
parser.add_argument('prompt', metavar='PROMPT', nargs='?', help='One question; omitted reads stdin or starts terminal chat')
|
|
20
|
+
parser.add_argument('--spec', type=Path, metavar='CHAT.json', help='Chat request JSON; mutually exclusive with prompt/stdin')
|
|
21
|
+
parser.add_argument('--system', help='System message; use messages in --spec instead when supplying a file')
|
|
22
|
+
parser.add_argument('--temperature', type=float)
|
|
23
|
+
parser.add_argument('--max-tokens', type=int)
|
|
24
|
+
parser.add_argument('--timeout-seconds', type=float, default=120, help='Per-request connection/read timeout (default: 120)')
|
|
25
|
+
parser.add_argument('--json', action='store_true', help='Return a complete non-streamed response for one question')
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def prepare(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None:
|
|
29
|
+
piped = '' if sys.stdin.isatty() else sys.stdin.read(1024 * 1024 + 1)
|
|
30
|
+
if args.spec is not None and (args.prompt is not None or piped or args.system is not None):
|
|
31
|
+
parser.error('--spec is mutually exclusive with PROMPT, stdin and --system')
|
|
32
|
+
if args.prompt is not None and piped:
|
|
33
|
+
parser.error('provide a question once, as PROMPT or stdin')
|
|
34
|
+
payload: dict[str, Any] = {}
|
|
35
|
+
if args.spec is not None:
|
|
36
|
+
try:
|
|
37
|
+
with args.spec.open(encoding='utf-8') as source:
|
|
38
|
+
raw = source.read(1024 * 1024 + 1)
|
|
39
|
+
if len(raw.encode()) > 1024 * 1024:
|
|
40
|
+
raise ValueError
|
|
41
|
+
payload = json.loads(raw)
|
|
42
|
+
if not isinstance(payload, dict) or 'messages' not in payload:
|
|
43
|
+
raise ValueError
|
|
44
|
+
except (OSError, UnicodeError, ValueError):
|
|
45
|
+
parser.error('--spec requires a readable chat JSON object smaller than 1 MiB with messages')
|
|
46
|
+
args.chat_interactive = args.prompt is None and args.spec is None and sys.stdin.isatty()
|
|
47
|
+
if args.chat_interactive and args.json:
|
|
48
|
+
parser.error('--json requires PROMPT, stdin or --spec')
|
|
49
|
+
if not payload:
|
|
50
|
+
messages = [{'role': 'system', 'content': args.system}] if args.system is not None else []
|
|
51
|
+
if not args.chat_interactive:
|
|
52
|
+
prompt = args.prompt if args.prompt is not None else piped
|
|
53
|
+
if not prompt.strip():
|
|
54
|
+
parser.error('chat requires a non-empty question')
|
|
55
|
+
messages.append({'role': 'user', 'content': prompt})
|
|
56
|
+
payload['messages'] = messages
|
|
57
|
+
if 'stream' in payload:
|
|
58
|
+
parser.error('omit stream from --spec; text output streams and --json returns a complete response')
|
|
59
|
+
for field in ('temperature', 'max_tokens'):
|
|
60
|
+
if (value := getattr(args, field)) is not None:
|
|
61
|
+
payload[field] = value
|
|
62
|
+
try:
|
|
63
|
+
validate([{'role': 'user', 'content': 'validation'}] if args.chat_interactive else payload['messages'], args.timeout_seconds,
|
|
64
|
+
{k: v for k, v in payload.items() if k != 'messages'})
|
|
65
|
+
except (ValueError, TypeError):
|
|
66
|
+
parser.error('chat requires valid messages, sampling parameters and a finite positive timeout')
|
|
67
|
+
args.chat_payload = payload
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _answer(jobs: Any, job_id: str, payload: dict[str, Any], timeout_seconds: float) -> str:
|
|
71
|
+
text: list[str] = []
|
|
72
|
+
iterator = cast(Generator[dict[str, Any], None, None], jobs.chat(job_id, stream=True, timeout_seconds=timeout_seconds, **payload))
|
|
73
|
+
with closing(iterator):
|
|
74
|
+
for chunk in iterator:
|
|
75
|
+
for choice in chunk['choices']:
|
|
76
|
+
delta = choice['delta']
|
|
77
|
+
if delta.get('tool_calls') or delta.get('function_call'):
|
|
78
|
+
raise RemoteError('CHAT_TEXT_UNAVAILABLE')
|
|
79
|
+
content = delta.get('content')
|
|
80
|
+
if content is not None and not isinstance(content, str):
|
|
81
|
+
raise RemoteError('INVALID_RESPONSE')
|
|
82
|
+
if content:
|
|
83
|
+
text.append(content)
|
|
84
|
+
print(safe_text(content), end='', flush=True)
|
|
85
|
+
if not text:
|
|
86
|
+
raise RemoteError('CHAT_TEXT_UNAVAILABLE')
|
|
87
|
+
print(flush=True)
|
|
88
|
+
return ''.join(text)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def run(args: argparse.Namespace, client: Any) -> int:
|
|
92
|
+
require_dependencies()
|
|
93
|
+
payload = args.chat_payload
|
|
94
|
+
if not args.chat_interactive:
|
|
95
|
+
if args.json:
|
|
96
|
+
response = client.jobs.chat(args.job_id, timeout_seconds=args.timeout_seconds, **payload)
|
|
97
|
+
print(json.dumps(response, ensure_ascii=False))
|
|
98
|
+
else:
|
|
99
|
+
_answer(client.jobs, args.job_id, payload, args.timeout_seconds)
|
|
100
|
+
return 0
|
|
101
|
+
history = list(payload['messages'])
|
|
102
|
+
initial = list(history)
|
|
103
|
+
print('Enter a message. /clear resets history; /exit, Ctrl+D or Ctrl+C exits. The Job stays running.', file=sys.stderr)
|
|
104
|
+
while True:
|
|
105
|
+
print('You> ', end='', file=sys.stderr, flush=True)
|
|
106
|
+
line = sys.stdin.readline()
|
|
107
|
+
if not line or line.strip() == '/exit':
|
|
108
|
+
return 0
|
|
109
|
+
if line.strip() == '/clear':
|
|
110
|
+
history = list(initial)
|
|
111
|
+
continue
|
|
112
|
+
if not line.strip():
|
|
113
|
+
continue
|
|
114
|
+
messages = [*history, {'role': 'user', 'content': line.rstrip('\n')}]
|
|
115
|
+
answer = _answer(client.jobs, args.job_id, {**payload, 'messages': messages}, args.timeout_seconds)
|
|
116
|
+
history = [*messages, {'role': 'assistant', 'content': answer}]
|
envloop_chat/client.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Job-bound OpenAI-compatible chat with explicit EnvLoop authentication."""
|
|
2
|
+
import copy
|
|
3
|
+
import importlib.util
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Generator
|
|
8
|
+
from typing import TYPE_CHECKING, Any, cast, override
|
|
9
|
+
from urllib.parse import quote
|
|
10
|
+
|
|
11
|
+
from envloop._optional import MissingFeatureError
|
|
12
|
+
from envloop.http import USER_AGENT, HttpService, RemoteError, retry_after_seconds
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from openai.types.chat import ChatCompletionMessageParam
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def require_dependencies() -> None:
|
|
19
|
+
if importlib.util.find_spec('openai') is None:
|
|
20
|
+
raise MissingFeatureError('chat')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def validate(messages: Any, timeout_seconds: float, options: dict[str, Any]) -> None:
|
|
24
|
+
if (not isinstance(messages, list) or not messages or any(not isinstance(m, dict)
|
|
25
|
+
or m.get('role') not in {'system', 'developer', 'user', 'assistant', 'tool', 'function'} for m in messages)):
|
|
26
|
+
raise ValueError('chat requires a non-empty messages array with valid roles')
|
|
27
|
+
if isinstance(timeout_seconds, bool) or not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
|
|
28
|
+
raise ValueError('chat timeout_seconds must be finite and positive')
|
|
29
|
+
if options.get('n', 1) != 1:
|
|
30
|
+
raise ValueError('chat supports one completion per request')
|
|
31
|
+
if 'max_tokens' in options and (type(options['max_tokens']) is not int or options['max_tokens'] <= 0):
|
|
32
|
+
raise ValueError('max_tokens must be a positive integer')
|
|
33
|
+
if 'temperature' in options:
|
|
34
|
+
value = options['temperature']
|
|
35
|
+
if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
|
|
36
|
+
raise ValueError('temperature must be finite and nonnegative')
|
|
37
|
+
if set(options) & {'extra_body', 'extra_headers', 'extra_query', 'base_url', 'api_key', 'timeout'}:
|
|
38
|
+
raise ValueError('chat connection settings come from the EnvLoop client')
|
|
39
|
+
try:
|
|
40
|
+
if len(json.dumps({'messages': messages, **options}, allow_nan=False).encode()) > 1024 * 1024 - 1024:
|
|
41
|
+
raise ValueError
|
|
42
|
+
except (ValueError, TypeError):
|
|
43
|
+
raise ValueError('chat request must be JSON and smaller than 1 MiB') from None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _error(error: Exception) -> RemoteError:
|
|
47
|
+
from openai import (
|
|
48
|
+
APIConnectionError,
|
|
49
|
+
APIError,
|
|
50
|
+
APIResponseValidationError,
|
|
51
|
+
APIStatusError,
|
|
52
|
+
APITimeoutError,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
if isinstance(error, APITimeoutError):
|
|
56
|
+
return RemoteError('REQUEST_TIMEOUT')
|
|
57
|
+
if isinstance(error, APIStatusError):
|
|
58
|
+
code = error.code
|
|
59
|
+
# Never retain arbitrary provider text, request bodies or exception messages.
|
|
60
|
+
safe = code if isinstance(code, str) and re.fullmatch(r'[A-Z][A-Z0-9_]{0,127}', code) else 'HTTP_ERROR'
|
|
61
|
+
return RemoteError(safe, error.status_code,
|
|
62
|
+
retry_after=retry_after_seconds(error.response.headers.get('Retry-After')))
|
|
63
|
+
if isinstance(error, APIConnectionError):
|
|
64
|
+
return RemoteError('NETWORK_ERROR')
|
|
65
|
+
if isinstance(error, APIResponseValidationError):
|
|
66
|
+
return RemoteError('INVALID_RESPONSE')
|
|
67
|
+
if isinstance(error, APIError):
|
|
68
|
+
return RemoteError('MODEL_CONNECTION_FAILED')
|
|
69
|
+
return RemoteError('INVALID_RESPONSE')
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _stream(connection: Any, model: str, messages: list[dict[str, Any]], options: dict[str, Any]) -> Generator[dict[str, Any], None, None]:
|
|
73
|
+
finished = False
|
|
74
|
+
try:
|
|
75
|
+
with connection, connection.chat.completions.create(
|
|
76
|
+
model=model, messages=messages, stream=True, extra_body=options) as response:
|
|
77
|
+
for event in response:
|
|
78
|
+
value = event.model_dump(mode='json')
|
|
79
|
+
choices = value.get('choices')
|
|
80
|
+
if not isinstance(choices, list):
|
|
81
|
+
raise RemoteError('INVALID_RESPONSE')
|
|
82
|
+
for choice in choices:
|
|
83
|
+
if not isinstance(choice, dict) or not isinstance(choice.get('delta'), dict):
|
|
84
|
+
raise RemoteError('INVALID_RESPONSE')
|
|
85
|
+
if choice.get('finish_reason') is not None:
|
|
86
|
+
finished = True
|
|
87
|
+
yield value
|
|
88
|
+
if not finished:
|
|
89
|
+
raise RemoteError('RESPONSE_INTERRUPTED')
|
|
90
|
+
except RemoteError:
|
|
91
|
+
raise
|
|
92
|
+
except Exception as error:
|
|
93
|
+
raise _error(error) from None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def chat(server: Any, job_id: str, *, messages: list[dict[str, Any]], stream: bool = False,
|
|
97
|
+
timeout_seconds: float = 120, **options: Any) -> dict[str, Any] | Generator[dict[str, Any], None, None]:
|
|
98
|
+
require_dependencies()
|
|
99
|
+
validate(messages, timeout_seconds, options)
|
|
100
|
+
if not isinstance(job_id, str) or not job_id.strip() or type(stream) is not bool:
|
|
101
|
+
raise ValueError('chat requires a Job ID and a boolean stream option')
|
|
102
|
+
if not isinstance(server, HttpService):
|
|
103
|
+
raise ValueError('chat requires Client.remote with an EnvLoop API connection')
|
|
104
|
+
query = copy.copy(server)
|
|
105
|
+
query.timeout = timeout_seconds
|
|
106
|
+
job = query.request('GET', '/v1/jobs/' + quote(job_id, safe=''))
|
|
107
|
+
if not isinstance(job, dict) or job.get('job_id') != job_id or job.get('type') != 'inference':
|
|
108
|
+
raise ValueError('chat requires an Inference Job')
|
|
109
|
+
inference = job.get('inference') or {}
|
|
110
|
+
if not isinstance(inference, dict) or inference.get('service_status') != 'READY':
|
|
111
|
+
raise RemoteError('ENDPOINT_NOT_READY')
|
|
112
|
+
model = inference.get('model')
|
|
113
|
+
if not isinstance(model, str) or not model:
|
|
114
|
+
raise RemoteError('INVALID_RESPONSE')
|
|
115
|
+
if options.pop('model', model) != model:
|
|
116
|
+
raise ValueError('chat model must match the Inference Job model')
|
|
117
|
+
from openai import DefaultHttpxClient, OpenAI
|
|
118
|
+
|
|
119
|
+
class JobOpenAI(OpenAI):
|
|
120
|
+
@property
|
|
121
|
+
@override
|
|
122
|
+
def default_headers(self) -> dict[str, Any]:
|
|
123
|
+
# The SDK merges OPENAI_CUSTOM_HEADERS into defaults even when a Key is
|
|
124
|
+
# explicit. Only the EnvLoop connection owns headers for this client.
|
|
125
|
+
return {'Accept': 'application/json', 'User-Agent': USER_AGENT, **server.headers}
|
|
126
|
+
|
|
127
|
+
connection = JobOpenAI(base_url=server.base + '/v1/jobs/' + quote(job_id, safe='') + '/inference',
|
|
128
|
+
api_key=server.secret or '', admin_api_key='', organization='', project='', max_retries=0,
|
|
129
|
+
timeout=timeout_seconds, default_headers=dict(server.headers),
|
|
130
|
+
_strict_response_validation=True,
|
|
131
|
+
http_client=DefaultHttpxClient(follow_redirects=False, trust_env=False))
|
|
132
|
+
if stream:
|
|
133
|
+
return _stream(connection, model, messages, options)
|
|
134
|
+
try:
|
|
135
|
+
with connection:
|
|
136
|
+
result = connection.chat.completions.create(model=model, messages=cast('list[ChatCompletionMessageParam]', messages),
|
|
137
|
+
stream=False, extra_body=options)
|
|
138
|
+
value = result.model_dump(mode='json')
|
|
139
|
+
if (not isinstance(value.get('choices'), list) or not value['choices']
|
|
140
|
+
or any(choice.get('finish_reason') is None for choice in value['choices'])):
|
|
141
|
+
raise RemoteError('INVALID_RESPONSE')
|
|
142
|
+
return value
|
|
143
|
+
except RemoteError:
|
|
144
|
+
raise
|
|
145
|
+
except Exception as error:
|
|
146
|
+
raise _error(error) from None
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: envloop-cli
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.2.0
|
|
4
4
|
Summary: EnvLoop CLI and Python SDK for jobs, training, checkpoints and inference
|
|
5
5
|
Project-URL: Homepage, https://envloop.ai
|
|
6
6
|
Project-URL: Documentation, https://docs.envloop.ai
|
|
@@ -10,7 +10,9 @@ Project-URL: Agent instructions, https://docs.envloop.ai/skill.md
|
|
|
10
10
|
Requires-Python: >=3.12
|
|
11
11
|
Provides-Extra: asset
|
|
12
12
|
Requires-Dist: boto3==1.44.3; extra == 'asset'
|
|
13
|
-
Requires-Dist: envloop-envhub==
|
|
13
|
+
Requires-Dist: envloop-envhub==2.2.0; extra == 'asset'
|
|
14
|
+
Provides-Extra: chat
|
|
15
|
+
Requires-Dist: openai==3.55.1; extra == 'chat'
|
|
14
16
|
Provides-Extra: default
|
|
15
17
|
Provides-Extra: experiment
|
|
16
18
|
Provides-Extra: rsi-loop
|
|
@@ -24,29 +26,16 @@ commands are equivalent. The Python import package is `envloop`.
|
|
|
24
26
|
|
|
25
27
|
## Release compatibility
|
|
26
28
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
release. Check your installed `el --version` and `el COMMAND --help` before
|
|
31
|
-
following an example; the source package version alone does not identify
|
|
32
|
-
unreleased features.
|
|
33
|
-
|
|
34
|
-
| Unreleased source enhancement | Published 1.33.0 |
|
|
35
|
-
| --- | --- |
|
|
36
|
-
| Explicit `--json` for `el runner get\|create\|update\|delete` | These commands already output JSON; omit `--json` |
|
|
37
|
-
| `el dataset create --format harbor --update-digests` | not available; set `[[tasks]] digest` values by hand |
|
|
38
|
-
| `el trial artifact download TRIAL_ID --output DIRECTORY` | positional `DIRECTORY` only |
|
|
39
|
-
|
|
40
|
-
Execution also requires a matching platform, project permissions and published
|
|
41
|
-
Runners; package installation alone does not establish those prerequisites. See the
|
|
29
|
+
Check your installed `el --version` and `el COMMAND --help` when following an
|
|
30
|
+
example. Upgrade an older installation with `uv tool upgrade envloop-cli`, or
|
|
31
|
+
`python -m pip install --upgrade envloop-cli` in your SDK environment. See the
|
|
42
32
|
[PyPI release history](https://pypi.org/project/envloop-cli/#history) for published versions.
|
|
43
33
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
available while waiting for a compatible platform release.
|
|
34
|
+
Job execution needs project permissions, readable published Runners and a
|
|
35
|
+
platform that supports the selected Profile and Runner formats. If the platform
|
|
36
|
+
rejects a format, ask your project administrator which published versions it
|
|
37
|
+
supports. Use `envloop-cli[chat]` for the Job chat examples below and
|
|
38
|
+
`envloop-cli[asset]` for ANS parsing and verified content transfers.
|
|
50
39
|
|
|
51
40
|
## Install
|
|
52
41
|
|
|
@@ -104,6 +93,21 @@ python -m pip install "envloop-cli[asset]"
|
|
|
104
93
|
|
|
105
94
|
## Connect
|
|
106
95
|
|
|
96
|
+
For Job-bound chat, install the optional dependency in the same environment:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
python -m pip install "envloop-cli[chat]"
|
|
100
|
+
el job chat JOB_ID "Introduce yourself."
|
|
101
|
+
el job chat JOB_ID
|
|
102
|
+
el job chat JOB_ID "Hello" --json
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Text answers stream by default. `--json` returns one complete response.
|
|
106
|
+
The command uses the configured EnvLoop connection and automatically reads the
|
|
107
|
+
Job's model. The `chat` extra uses the official OpenAI Python SDK against EnvLoop;
|
|
108
|
+
it does not use an OpenAI account. `/clear` resets terminal history, `/exit` leaves,
|
|
109
|
+
and Ctrl+C exits without stopping the Job.
|
|
110
|
+
|
|
107
111
|
Use an authorized EnvLoop account and project. Browser authorization:
|
|
108
112
|
|
|
109
113
|
```bash
|
|
@@ -215,19 +219,24 @@ Sandbox Job without a Dataset:
|
|
|
215
219
|
```bash
|
|
216
220
|
el job submit --type sandbox --runner base --command 'python --version'
|
|
217
221
|
el job submit --type sandbox --runner base --image python:3.11 --wait
|
|
222
|
+
el job submit --type sandbox --provider e2b --spec REQUEST.json
|
|
218
223
|
el job list --type sandbox
|
|
219
224
|
el job log JOB_ID --follow
|
|
220
225
|
```
|
|
221
226
|
|
|
222
227
|
The platform resolves `base` to the registered `envloop/base@main` source ref and
|
|
223
228
|
freezes its immutable Revision. The Sandbox image defaults to the registered Runner image;
|
|
224
|
-
`--image` accepts an image name, tag or digest.
|
|
225
|
-
by
|
|
229
|
+
`--image` accepts an image name, tag or digest. Bench and Sandbox submissions can request a
|
|
230
|
+
platform-enabled provider by name. In a request file, `provider` is a
|
|
231
|
+
top-level field alongside `spec` and optional `overrides` in an `envloop.job/v2`
|
|
232
|
+
envelope. The `--provider` flag overrides that field and also works with the
|
|
233
|
+
named `--profile` shortcut. Omit the selection to use the platform default.
|
|
234
|
+
Job logs retain the actual captured output and collection metadata.
|
|
226
235
|
Failures include a code, readable explanation, HTTP status when available, and
|
|
227
236
|
recovery guidance without echoing arbitrary response bodies or credentials.
|
|
228
237
|
|
|
229
238
|
Bench/Sandbox Harbor Recipes accept `--harbor_env docker|process` with a canonical
|
|
230
|
-
JobSpec (`spec.schema = "envloop.job/
|
|
239
|
+
JobSpec (`spec.schema = "envloop.job/v2"`) or a named `--profile`:
|
|
231
240
|
|
|
232
241
|
```bash
|
|
233
242
|
el job submit --type sandbox --spec REQUEST.json --harbor_env process
|
|
@@ -388,8 +397,9 @@ ID is never substituted for a real asset ID. Use `RESOURCE upload get OPERATION_
|
|
|
388
397
|
only publication commit; there is no separate upload create command. Failed or timed-out operations
|
|
389
398
|
exit nonzero while preserving their safe receipt. Storage credentials are not printed.
|
|
390
399
|
|
|
391
|
-
Dataset downloads require an explicit split and accept
|
|
392
|
-
digest selectors.
|
|
400
|
+
Dataset downloads require an explicit split and accept content digest and paired task ID/tree
|
|
401
|
+
digest selectors. Directory downloads with an explicit config selector are currently unsupported
|
|
402
|
+
by the pinned ANS dependency. Downloads verify manifests, sizes, SHA-256, safe paths and executable bits. Use
|
|
393
403
|
`download REF --file-id FILE_ID --output FILE --resume` for a resumable single file. File selection
|
|
394
404
|
is separate from `get`; Profile uses a redacted `export` instead of a content download.
|
|
395
405
|
|