-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path__client_async_template.py
More file actions
530 lines (463 loc) · 19.3 KB
/
__client_async_template.py
File metadata and controls
530 lines (463 loc) · 19.3 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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
"""Agent Runtime 客户端 / Agent Runtime Client
此模块提供 Agent Runtime 的客户端API,用于管理智能体运行时。
This module provides the client API for Agent Runtime to manage agent runtimes.
"""
from typing import List, Optional
from alibabacloud_agentrun20250910.models import (
CreateAgentRuntimeEndpointInput,
CreateAgentRuntimeInput,
GetAgentRuntimeRequest,
ListAgentRuntimeEndpointsRequest,
ListAgentRuntimesRequest,
ListAgentRuntimeVersionsRequest,
UpdateAgentRuntimeEndpointInput,
UpdateAgentRuntimeInput,
)
from typing_extensions import Unpack
from agentrun.agent_runtime._workspace import (
resolve_workspace_id_by_name,
resolve_workspace_id_by_name_async,
resolve_workspace_ids_by_names,
resolve_workspace_ids_by_names_async,
)
from agentrun.agent_runtime.api.data import InvokeArgs
from agentrun.agent_runtime.model import (
AgentRuntimeArtifact,
AgentRuntimeCreateInput,
AgentRuntimeEndpointCreateInput,
AgentRuntimeEndpointListInput,
AgentRuntimeEndpointUpdateInput,
AgentRuntimeListInput,
AgentRuntimeUpdateInput,
AgentRuntimeVersion,
AgentRuntimeVersionListInput,
NetworkConfig,
)
from agentrun.agent_runtime.runtime import AgentRuntime
from agentrun.utils.config import Config
from agentrun.utils.exception import HTTPError
from .api import AgentRuntimeControlAPI, AgentRuntimeDataAPI
from .endpoint import AgentRuntimeEndpoint
class AgentRuntimeClient:
"""Agent Runtime 客户端 / Agent Runtime Client
提供 Agent Runtime 的创建、删除、更新、查询和端点管理功能。
Provides create, delete, update, query and endpoint management functions for Agent Runtime.
"""
def __init__(self, config: Optional[Config] = None):
"""初始化客户端 / Initialize client
Args:
config: 配置对象,可选 / Configuration object, optional
"""
self.config = config
self.__control_api = AgentRuntimeControlAPI(config)
async def create_async(
self, input: AgentRuntimeCreateInput, config: Optional[Config] = None
) -> AgentRuntime:
"""异步创建 Agent Runtime / Create Agent Runtime asynchronously
Args:
input: Agent Runtime 创建配置 / Agent Runtime creation configuration
config: 配置对象,可选 / Configuration object, optional
Returns:
AgentRuntime: 创建的 Agent Runtime 对象 / Created Agent Runtime object
Raises:
ValueError: 当既未提供代码配置也未提供容器配置时;或同时传入
workspace_id 与 workspace_name / When neither code nor container
configuration is provided, or when workspace_id and workspace_name
are both set
ResourceAlreadyExistError: 资源已存在 / Resource already exists
ResourceNotExistError: 资源不存在;或 workspace_name 在该账号下未找到
/ Resource does not exist, or no workspace matches workspace_name
HTTPError: HTTP 请求错误 / HTTP request error
"""
if input.workspace_id and input.workspace_name:
raise ValueError(
"workspace_id and workspace_name are mutually exclusive; please"
" only set one of them."
)
if input.workspace_name is not None:
cfg = Config.with_configs(self.config, config)
resolved_id = await resolve_workspace_id_by_name_async(
input.workspace_name, cfg
)
input = input.model_copy(
update={"workspace_id": resolved_id, "workspace_name": None}
)
if input.network_configuration is None:
input.network_configuration = NetworkConfig()
if input.artifact_type is None:
if input.code_configuration is not None:
input.artifact_type = AgentRuntimeArtifact.CODE
elif input.container_configuration is not None:
input.artifact_type = AgentRuntimeArtifact.CONTAINER
else:
raise ValueError(
"Either code_configuration or image_configuration must be"
" provided."
)
try:
result = await self.__control_api.create_agent_runtime_async(
CreateAgentRuntimeInput().from_map(input.model_dump()),
config=config,
)
except HTTPError as e:
raise e.to_resource_error(
"AgentRuntime", input.agent_runtime_name
) from e
return AgentRuntime.from_inner_object(result)
async def delete_async(
self, id: str, config: Optional[Config] = None
) -> AgentRuntime:
"""异步删除 Agent Runtime / Delete Agent Runtime asynchronously
Args:
id: Agent Runtime ID
config: 配置对象,可选 / Configuration object, optional
Returns:
AgentRuntime: 删除的 Agent Runtime 对象 / Deleted Agent Runtime object
Raises:
ResourceNotExistError: 资源不存在 / Resource does not exist
HTTPError: HTTP 请求错误 / HTTP request error
"""
try:
result = await self.__control_api.delete_agent_runtime_async(
id, config=config
)
# Delete 响应只有 agentRuntimeId 有效,其他字段为空字符串/零值,
# 走 from_inner_object 会在 status/artifactType 等 Enum 字段上触发
# 伪校验错误。这里直接构造一个只带 id 的极简对象。
return AgentRuntime.model_construct(
agent_runtime_id=result.agent_runtime_id
)
except HTTPError as e:
raise e.to_resource_error("AgentRuntime", id) from e
async def update_async(
self,
id: str,
input: AgentRuntimeUpdateInput,
config: Optional[Config] = None,
) -> AgentRuntime:
"""异步更新 Agent Runtime / Update Agent Runtime asynchronously
Args:
id: Agent Runtime ID
input: Agent Runtime 更新配置 / Agent Runtime update configuration
config: 配置对象,可选 / Configuration object, optional
Returns:
AgentRuntime: 更新后的 Agent Runtime 对象 / Updated Agent Runtime object
Raises:
ResourceNotExistError: 资源不存在 / Resource does not exist
HTTPError: HTTP 请求错误 / HTTP request error
"""
try:
result = await self.__control_api.update_agent_runtime_async(
id,
UpdateAgentRuntimeInput().from_map(input.model_dump()),
config=config,
)
return AgentRuntime.from_inner_object(result)
except HTTPError as e:
raise e.to_resource_error("AgentRuntime", id) from e
async def get_async(
self,
id: str,
config: Optional[Config] = None,
) -> AgentRuntime:
"""异步获取 Agent Runtime / Get Agent Runtime asynchronously
Args:
id: Agent Runtime ID
config: 配置对象,可选 / Configuration object, optional
Returns:
AgentRuntime: Agent Runtime 对象 / Agent Runtime object
Raises:
ResourceNotExistError: 资源不存在 / Resource does not exist
HTTPError: HTTP 请求错误 / HTTP request error
"""
try:
result = await self.__control_api.get_agent_runtime_async(
id, GetAgentRuntimeRequest(), config=config
)
return AgentRuntime.from_inner_object(result)
except HTTPError as e:
raise e.to_resource_error("AgentRuntime", id) from e
async def list_async(
self,
input: Optional[AgentRuntimeListInput] = None,
config: Optional[Config] = None,
) -> List[AgentRuntime]:
"""异步列出 Agent Runtimes / List Agent Runtimes asynchronously
Args:
input: 列表查询配置,可选 / List query configuration, optional
config: 配置对象,可选 / Configuration object, optional
Returns:
List[AgentRuntime]: Agent Runtime 对象列表 / List of Agent Runtime objects
Raises:
ValueError: 同时传入 workspace_id 与 workspace_name,或同时传入
workspace_ids 与 workspace_names / When workspace_id and
workspace_name (or workspace_ids and workspace_names) are
both set
ResourceNotExistError: workspace_name(s) 在该账号下未找到
/ No workspace matches the given workspace_name(s)
HTTPError: HTTP 请求错误 / HTTP request error
"""
try:
if input is None:
input = AgentRuntimeListInput()
if input.workspace_id and input.workspace_name:
raise ValueError(
"workspace_id and workspace_name are mutually exclusive;"
" please only set one of them."
)
if input.workspace_ids and input.workspace_names:
raise ValueError(
"workspace_ids and workspace_names are mutually exclusive;"
" please only set one of them."
)
if input.workspace_name is not None or input.workspace_names:
cfg = Config.with_configs(self.config, config)
update: dict = {}
if input.workspace_name is not None:
update["workspace_id"] = (
await resolve_workspace_id_by_name_async(
input.workspace_name, cfg
)
)
update["workspace_name"] = None
if input.workspace_names:
update["workspace_ids"] = (
await resolve_workspace_ids_by_names_async(
input.workspace_names, cfg
)
)
update["workspace_names"] = None
input = input.model_copy(update=update)
results = await self.__control_api.list_agent_runtimes_async(
ListAgentRuntimesRequest().from_map(input.model_dump()),
config=config,
)
return [
AgentRuntime.from_inner_object(item) for item in results.items
]
except HTTPError as e:
raise e.to_resource_error("AgentRuntime") from e
async def create_endpoint_async(
self,
agent_runtime_id: str,
endpoint: AgentRuntimeEndpointCreateInput,
config: Optional[Config] = None,
) -> AgentRuntimeEndpoint:
"""异步创建 Agent Runtime 端点 / Create Agent Runtime Endpoint asynchronously
Args:
agent_runtime_id: Agent Runtime ID
endpoint: 端点创建配置 / Endpoint creation configuration
config: 配置对象,可选 / Configuration object, optional
Returns:
AgentRuntimeEndpoint: 创建的端点对象 / Created endpoint object
Raises:
ResourceAlreadyExistError: 资源已存在 / Resource already exists
ResourceNotExistError: Agent Runtime 不存在 / Agent Runtime does not exist
HTTPError: HTTP 请求错误 / HTTP request error
"""
try:
result = (
await self.__control_api.create_agent_runtime_endpoint_async(
agent_runtime_id,
CreateAgentRuntimeEndpointInput().from_map(
endpoint.model_dump()
),
config=config,
)
)
except HTTPError as e:
raise e.to_resource_error(
"AgentRuntimeEndpoint",
"/".join([
agent_runtime_id,
endpoint.agent_runtime_endpoint_name or "",
]),
) from e
return AgentRuntimeEndpoint.from_inner_object(result)
async def delete_endpoint_async(
self,
agent_runtime_id: str,
endpoint_id: str,
config: Optional[Config] = None,
) -> AgentRuntimeEndpoint:
"""异步删除 Agent Runtime 端点 / Delete Agent Runtime Endpoint asynchronously
Args:
agent_runtime_id: Agent Runtime ID
endpoint_id: 端点 ID / Endpoint ID
config: 配置对象,可选 / Configuration object, optional
Returns:
AgentRuntimeEndpoint: 删除的端点对象 / Deleted endpoint object
Raises:
ResourceNotExistError: 资源不存在 / Resource does not exist
HTTPError: HTTP 请求错误 / HTTP request error
"""
try:
result = (
await self.__control_api.delete_agent_runtime_endpoint_async(
agent_runtime_id,
endpoint_id,
config=config,
)
)
except HTTPError as e:
raise e.to_resource_error(
"AgentRuntimeEndpoint",
"/".join([
agent_runtime_id,
endpoint_id,
]),
) from e
return AgentRuntimeEndpoint.from_inner_object(result)
async def update_endpoint_async(
self,
agent_runtime_id: str,
endpoint_id: str,
endpoint: AgentRuntimeEndpointUpdateInput,
config: Optional[Config] = None,
) -> AgentRuntimeEndpoint:
"""异步更新 Agent Runtime 端点 / Update Agent Runtime Endpoint asynchronously
Args:
agent_runtime_id: Agent Runtime ID
endpoint_id: 端点 ID / Endpoint ID
endpoint: 端点更新配置 / Endpoint update configuration
config: 配置对象,可选 / Configuration object, optional
Returns:
AgentRuntimeEndpoint: 更新后的端点对象 / Updated endpoint object
Raises:
ResourceNotExistError: 资源不存在 / Resource does not exist
HTTPError: HTTP 请求错误 / HTTP request error
"""
try:
result = (
await self.__control_api.update_agent_runtime_endpoint_async(
agent_runtime_id,
endpoint_id,
UpdateAgentRuntimeEndpointInput().from_map(
endpoint.model_dump()
),
config=config,
)
)
except HTTPError as e:
raise e.to_resource_error(
"AgentRuntimeEndpoint",
"/".join([
agent_runtime_id,
endpoint_id,
]),
) from e
return AgentRuntimeEndpoint.from_inner_object(result)
async def get_endpoint_async(
self,
agent_runtime_id: str,
endpoint_id: str,
config: Optional[Config] = None,
) -> AgentRuntimeEndpoint:
"""异步获取 Agent Runtime 端点 / Get Agent Runtime Endpoint asynchronously
Args:
agent_runtime_id: Agent Runtime ID
endpoint_id: 端点 ID / Endpoint ID
config: 配置对象,可选 / Configuration object, optional
Returns:
AgentRuntimeEndpoint: 端点对象 / Endpoint object
Raises:
ResourceNotExistError: 资源不存在 / Resource does not exist
HTTPError: HTTP 请求错误 / HTTP request error
"""
try:
result = await self.__control_api.get_agent_runtime_endpoint_async(
agent_runtime_id,
endpoint_id,
config=config,
)
except HTTPError as e:
raise e.to_resource_error(
"AgentRuntimeEndpoint",
"/".join([
agent_runtime_id,
endpoint_id,
]),
) from e
return AgentRuntimeEndpoint.from_inner_object(result)
async def list_endpoints_async(
self,
agent_runtime_id: str,
input: Optional[AgentRuntimeEndpointListInput] = None,
config: Optional[Config] = None,
) -> List[AgentRuntimeEndpoint]:
"""异步列出 Agent Runtime 端点 / List Agent Runtime Endpoints asynchronously
Args:
agent_runtime_id: Agent Runtime ID
input: 列表查询配置,可选 / List query configuration, optional
config: 配置对象,可选 / Configuration object, optional
Returns:
List[AgentRuntimeEndpoint]: 端点对象列表 / List of endpoint objects
Raises:
HTTPError: HTTP 请求错误 / HTTP request error
"""
try:
if input is None:
input = AgentRuntimeEndpointListInput()
results = (
await self.__control_api.list_agent_runtime_endpoints_async(
agent_runtime_id,
ListAgentRuntimeEndpointsRequest().from_map(
input.model_dump()
),
config=config,
)
)
return [
AgentRuntimeEndpoint.from_inner_object(item)
for item in results.items
]
except HTTPError as e:
raise e.to_resource_error("AgentRuntime", agent_runtime_id) from e
async def list_versions_async(
self,
agent_runtime_id: str,
input: Optional[AgentRuntimeVersionListInput] = None,
config: Optional[Config] = None,
) -> List[AgentRuntimeVersion]:
"""异步列出 Agent Runtime 版本 / List Agent Runtime Versions asynchronously
Args:
agent_runtime_id: Agent Runtime ID
input: 列表查询配置,可选 / List query configuration, optional
config: 配置对象,可选 / Configuration object, optional
Returns:
List[AgentRuntimeVersion]: 版本对象列表 / List of version objects
Raises:
HTTPError: HTTP 请求错误 / HTTP request error
"""
try:
if input is None:
input = AgentRuntimeVersionListInput()
results = (
await self.__control_api.list_agent_runtime_versions_async(
agent_runtime_id,
ListAgentRuntimeVersionsRequest().from_map(
input.model_dump()
),
config=config,
)
)
return [
AgentRuntimeVersion.from_inner_object(item)
for item in results.items
]
except HTTPError as e:
raise e.to_resource_error("AgentRuntime", agent_runtime_id) from e
async def invoke_openai_async(
self,
agent_runtime_name: str,
agent_runtime_endpoint_name: str = "Default",
**kwargs: Unpack[InvokeArgs],
):
cfg = Config.with_configs(self.config, kwargs.get("config"))
kwargs["config"] = cfg
data_api = AgentRuntimeDataAPI(
agent_runtime_name=agent_runtime_name,
agent_runtime_endpoint_name=agent_runtime_endpoint_name,
config=cfg,
)
return await data_api.invoke_openai_async(**kwargs)