-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path__client_async_template.py
More file actions
491 lines (410 loc) · 15.1 KB
/
__client_async_template.py
File metadata and controls
491 lines (410 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
"""Sandbox客户端模板 / Sandbox Client Template
此模板用于生成沙箱客户端代码。
This template is used to generate sandbox client code.
"""
import time
from typing import Any, Dict, List, Optional, TYPE_CHECKING
from alibabacloud_agentrun20250910.models import (
CreateTemplateInput,
ListSandboxesRequest,
ListTemplatesRequest,
UpdateTemplateInput,
)
from agentrun.sandbox.api import SandboxControlAPI, SandboxDataAPI
from agentrun.sandbox.model import (
ListSandboxesInput,
ListSandboxesOutput,
NASConfig,
OSSMountConfig,
PageableInput,
PolarFsConfig,
TemplateInput,
)
from agentrun.utils.config import Config
from agentrun.utils.exception import (
AgentRunError,
ClientError,
ResourceNotExistError,
)
from .sandbox import Sandbox
if TYPE_CHECKING:
from agentrun.sandbox.template import Template
class SandboxClient:
"""Sandbox 客户端 / Sandbox Client
用于管理 Sandbox 和 Template。
Used for managing Sandboxes and Templates.
"""
def __init__(self, config: Optional[Config] = None):
"""初始化 Sandbox 客户端 / Initialize Sandbox client
Args:
config: 配置对象,可选 / Configuration object, optional
"""
self.__control_api = SandboxControlAPI(config=config)
self.__sandbox_data_api = SandboxDataAPI(config=config)
async def _wait_template_ready_async(
self,
template_name: str,
config: Optional[Config] = None,
interval_seconds: int = 5,
timeout_seconds: int = 300,
) -> "Template":
"""Wait for Template to be ready (async)
Args:
template_name: Template name
config: Config object
interval_seconds: Polling interval in seconds
timeout_seconds: Timeout in seconds
Returns:
Template: Ready Template object
Raises:
TimeoutError: Timeout error
ClientError: Client error
"""
import asyncio
start_time = time.time()
while True:
template = await self.get_template_async(
template_name, config=config
)
# Check if ready
if template.status == "READY":
return template
# Check if failed
if (
template.status == "CREATE_FAILED"
or template.status == "UPDATE_FAILED"
):
raise AgentRunError(
f"Template {template_name} creation failed, status:"
f" {template.status}"
)
# Check timeout
if time.time() - start_time > timeout_seconds:
raise TimeoutError(
f"Timeout waiting for Template {template_name} to be ready,"
f" current status: {template.status}"
)
await asyncio.sleep(interval_seconds)
async def create_template_async(
self, input: TemplateInput, config: Optional[Config] = None
) -> "Template":
"""创建 Template(异步)
Args:
input: Template 配置
config: 配置对象
Returns:
Template: 创建的 Template 对象
Raises:
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
# 转换为 SDK 需要的格式
sdk_input = CreateTemplateInput().from_map(
input.model_dump(by_alias=True)
)
result = await self.__control_api.create_template_async(
sdk_input, config=config
)
template = Template.from_inner_object(result)
# Poll and wait for Template to be ready
template = await self._wait_template_ready_async(
template.template_name or "", config=config
)
return template
async def delete_template_async(
self, template_name: str, config: Optional[Config] = None
) -> "Template":
"""删除 Template(异步)
Args:
template_name: Template 名称
config: 配置对象
Returns:
Template: 删除的 Template 对象
Raises:
ResourceNotExistError: Template 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
try:
result = await self.__control_api.delete_template_async(
template_name, config=config
)
return Template.from_inner_object(result)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Template", template_name) from e
raise e
async def update_template_async(
self,
template_name: str,
input: TemplateInput,
config: Optional[Config] = None,
) -> "Template":
"""更新 Template(异步)
Args:
template_name: Template 名称
input: Template 更新配置
config: 配置对象
Returns:
Template: 更新后的 Template 对象
Raises:
ResourceNotExistError: Template 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
try:
# 转换为 SDK 需要的格式
sdk_input = UpdateTemplateInput().from_map(
input.model_dump(by_alias=True, exclude_none=True)
)
result = await self.__control_api.update_template_async(
template_name, sdk_input, config=config
)
return Template.from_inner_object(result)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Template", template_name) from e
raise e
async def get_template_async(
self, template_name: str, config: Optional[Config] = None
) -> "Template":
"""获取 Template(异步)
Args:
template_name: Template 名称
config: 配置对象
Returns:
Template: Template 对象
Raises:
ResourceNotExistError: Template 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
from agentrun.sandbox.template import Template
try:
result = await self.__control_api.get_template_async(
template_name, config=config
)
return Template.from_inner_object(result)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Template", template_name) from e
raise e
async def list_templates_async(
self,
input: Optional[PageableInput] = None,
config: Optional[Config] = None,
) -> List["Template"]:
"""枚举 Templates(异步)
Args:
input: 分页配置
config: 配置对象
Returns:
List[Template]: Template 列表
Raises:
ClientError: 客户端错误
ServerError: 服务器错误
TimeoutError: Timeout waiting for Template to be ready
"""
from agentrun.sandbox.template import Template
if input is None:
input = PageableInput()
# 转换为 SDK 需要的格式
sdk_input = ListTemplatesRequest().from_map(
input.model_dump(by_alias=True)
)
results = await self.__control_api.list_templates_async(
sdk_input, config=config
)
return (
[Template.from_inner_object(item) for item in results.items]
if results.items
else []
)
async def create_sandbox_async(
self,
template_name: str,
sandbox_idle_timeout_seconds: Optional[int] = 600,
nas_config: Optional[NASConfig] = None,
oss_mount_config: Optional[OSSMountConfig] = None,
polar_fs_config: Optional[PolarFsConfig] = None,
config: Optional[Config] = None,
) -> Sandbox:
"""创建 Sandbox(异步) / Create Sandbox (async)
Args:
template_name: 模板名称 / Template name
sandbox_idle_timeout_seconds: 沙箱空闲超时时间(秒) / Sandbox idle timeout (seconds)
nas_config: NAS 配置 / NAS configuration
oss_mount_config: OSS 挂载配置 / OSS mount configuration
polar_fs_config: PolarFS 配置 / PolarFS configuration
config: 配置对象 / Config object
Returns:
Sandbox: 创建的 Sandbox 对象 / Created Sandbox object
Raises:
ClientError: 客户端错误 / Client error
ServerError: 服务器错误 / Server error
"""
# 将配置对象转换为字典格式
nas_config_dict: Optional[Dict[str, Any]] = None
if nas_config is not None:
nas_config_dict = nas_config.model_dump(by_alias=True)
oss_mount_config_dict: Optional[Dict[str, Any]] = None
if oss_mount_config is not None:
oss_mount_config_dict = oss_mount_config.model_dump(by_alias=True)
polar_fs_config_dict: Optional[Dict[str, Any]] = None
if polar_fs_config is not None:
polar_fs_config_dict = polar_fs_config.model_dump(by_alias=True)
result = await self.__sandbox_data_api.create_sandbox_async(
template_name=template_name,
sandbox_idle_timeout_seconds=sandbox_idle_timeout_seconds,
nas_config=nas_config_dict,
oss_mount_config=oss_mount_config_dict,
polar_fs_config=polar_fs_config_dict,
config=config,
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
raise ClientError(
status_code=0,
message=(
"Failed to create sandbox:"
f" {result.get('message', 'Unknown error')}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
async def stop_sandbox_async(
self, sandbox_id: str, config: Optional[Config] = None
) -> Sandbox:
"""停止 Sandbox(异步)
Args:
sandbox_id: Sandbox ID
config: 配置对象
Returns:
Sandbox: 停止后的 Sandbox 对象
Raises:
ResourceNotExistError: Sandbox 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
try:
result = await self.__sandbox_data_api.stop_sandbox_async(
sandbox_id
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
raise ClientError(
status_code=0,
message=(
"Failed to stop sandbox:"
f" {result.get('message', 'Unknown error')}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Sandbox", sandbox_id) from e
raise e
async def delete_sandbox_async(
self, sandbox_id: str, config: Optional[Config] = None
) -> Sandbox:
"""删除 Sandbox(异步)
Args:
sandbox_id: Sandbox ID
config: 配置对象
Returns:
Sandbox: 停止后的 Sandbox 对象
Raises:
ResourceNotExistError: Sandbox 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
try:
result = await self.__sandbox_data_api.delete_sandbox_async(
sandbox_id
)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
raise ClientError(
status_code=0,
message=(
"Failed to stop sandbox:"
f" {result.get('message', 'Unknown error')}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Sandbox", sandbox_id) from e
raise e
async def get_sandbox_async(
self,
sandbox_id: str,
config: Optional[Config] = None,
) -> Sandbox:
"""获取 Sandbox(异步)
Args:
sandbox_id: Sandbox ID
config: 配置对象
Returns:
Sandbox: Sandbox 对象
Raises:
ResourceNotExistError: Sandbox 不存在
ClientError: 客户端错误
ServerError: 服务器错误
"""
try:
result = await self.__sandbox_data_api.get_sandbox_async(sandbox_id)
# 判断返回结果是否成功
if result.get("code") != "SUCCESS":
raise ClientError(
status_code=0,
message=(
"Failed to get sandbox:"
f" {result.get('message', 'Unknown error')}"
),
)
# 从 data 字段中提取数据并实例化(使用 model_validate 从字典创建)
data = result.get("data", {})
return Sandbox.model_validate(data, by_alias=True)
except ClientError as e:
if e.status_code == 404:
raise ResourceNotExistError("Sandbox", sandbox_id) from e
raise e
async def list_sandboxes_async(
self,
input: Optional[ListSandboxesInput] = None,
config: Optional[Config] = None,
) -> ListSandboxesOutput:
"""枚举 Sandboxes(异步)
Args:
input: 分页配置
config: 配置对象
Returns:
List[Sandbox]: Sandbox 列表
Raises:
ClientError: 客户端错误
ServerError: 服务器错误
"""
if input is None:
input = ListSandboxesInput()
# 转换为 SDK 需要的格式
sdk_input = ListSandboxesRequest().from_map(
input.model_dump(by_alias=True)
)
results = await self.__control_api.list_sandboxes_async(
sdk_input, config=config
)
return ListSandboxesOutput(
sandboxes=[
Sandbox.from_inner_object(item) for item in results.items
],
next_token=results.next_token,
)