agentscope-runtime 0.1.4__py3-none-any.whl → 0.1.5b2__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.
Files changed (43) hide show
  1. agentscope_runtime/engine/agents/agentscope_agent/agent.py +3 -0
  2. agentscope_runtime/engine/deployers/__init__.py +13 -0
  3. agentscope_runtime/engine/deployers/adapter/responses/__init__.py +0 -0
  4. agentscope_runtime/engine/deployers/adapter/responses/response_api_adapter_utils.py +2886 -0
  5. agentscope_runtime/engine/deployers/adapter/responses/response_api_agent_adapter.py +51 -0
  6. agentscope_runtime/engine/deployers/adapter/responses/response_api_protocol_adapter.py +314 -0
  7. agentscope_runtime/engine/deployers/cli_fc_deploy.py +184 -0
  8. agentscope_runtime/engine/deployers/kubernetes_deployer.py +265 -0
  9. agentscope_runtime/engine/deployers/local_deployer.py +356 -501
  10. agentscope_runtime/engine/deployers/modelstudio_deployer.py +677 -0
  11. agentscope_runtime/engine/deployers/utils/__init__.py +0 -0
  12. agentscope_runtime/engine/deployers/utils/deployment_modes.py +14 -0
  13. agentscope_runtime/engine/deployers/utils/docker_image_utils/__init__.py +8 -0
  14. agentscope_runtime/engine/deployers/utils/docker_image_utils/docker_image_builder.py +429 -0
  15. agentscope_runtime/engine/deployers/utils/docker_image_utils/dockerfile_generator.py +240 -0
  16. agentscope_runtime/engine/deployers/utils/docker_image_utils/runner_image_factory.py +297 -0
  17. agentscope_runtime/engine/deployers/utils/package_project_utils.py +932 -0
  18. agentscope_runtime/engine/deployers/utils/service_utils/__init__.py +9 -0
  19. agentscope_runtime/engine/deployers/utils/service_utils/fastapi_factory.py +504 -0
  20. agentscope_runtime/engine/deployers/utils/service_utils/fastapi_templates.py +157 -0
  21. agentscope_runtime/engine/deployers/utils/service_utils/process_manager.py +268 -0
  22. agentscope_runtime/engine/deployers/utils/service_utils/service_config.py +75 -0
  23. agentscope_runtime/engine/deployers/utils/service_utils/service_factory.py +220 -0
  24. agentscope_runtime/engine/deployers/utils/wheel_packager.py +389 -0
  25. agentscope_runtime/engine/helpers/agent_api_builder.py +651 -0
  26. agentscope_runtime/engine/runner.py +36 -10
  27. agentscope_runtime/engine/schemas/agent_schemas.py +70 -2
  28. agentscope_runtime/engine/schemas/embedding.py +37 -0
  29. agentscope_runtime/engine/schemas/modelstudio_llm.py +310 -0
  30. agentscope_runtime/engine/schemas/oai_llm.py +538 -0
  31. agentscope_runtime/engine/schemas/realtime.py +254 -0
  32. agentscope_runtime/engine/services/mem0_memory_service.py +124 -0
  33. agentscope_runtime/engine/services/memory_service.py +2 -1
  34. agentscope_runtime/engine/services/redis_session_history_service.py +4 -3
  35. agentscope_runtime/engine/services/session_history_service.py +4 -3
  36. agentscope_runtime/sandbox/manager/container_clients/kubernetes_client.py +555 -10
  37. agentscope_runtime/version.py +1 -1
  38. {agentscope_runtime-0.1.4.dist-info → agentscope_runtime-0.1.5b2.dist-info}/METADATA +21 -4
  39. {agentscope_runtime-0.1.4.dist-info → agentscope_runtime-0.1.5b2.dist-info}/RECORD +43 -16
  40. {agentscope_runtime-0.1.4.dist-info → agentscope_runtime-0.1.5b2.dist-info}/entry_points.txt +1 -0
  41. {agentscope_runtime-0.1.4.dist-info → agentscope_runtime-0.1.5b2.dist-info}/WHEEL +0 -0
  42. {agentscope_runtime-0.1.4.dist-info → agentscope_runtime-0.1.5b2.dist-info}/licenses/LICENSE +0 -0
  43. {agentscope_runtime-0.1.4.dist-info → agentscope_runtime-0.1.5b2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,677 @@
1
+ # -*- coding: utf-8 -*-
2
+ # pylint:disable=too-many-nested-blocks, too-many-return-statements,
3
+ # pylint:disable=too-many-branches, too-many-statements, try-except-raise
4
+ # pylint:disable=ungrouped-imports, arguments-renamed, protected-access
5
+ #
6
+ # flake8: noqa: E501
7
+ import logging
8
+ import os
9
+ import time
10
+ import uuid
11
+ from pathlib import Path
12
+ from typing import Dict, Optional, List, Union, Tuple
13
+
14
+ from pydantic import BaseModel, Field
15
+
16
+ from .adapter.protocol_adapter import ProtocolAdapter
17
+ from .base import DeployManager
18
+ from .local_deployer import LocalDeployManager
19
+ from .utils.service_utils import (
20
+ ServicesConfig,
21
+ )
22
+ from .utils.wheel_packager import (
23
+ generate_wrapper_project,
24
+ build_wheel,
25
+ default_deploy_name,
26
+ )
27
+ from ..runner import Runner
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ try: # Lazy optional imports; validated at runtime
33
+ import alibabacloud_oss_v2 as oss # type: ignore
34
+ from alibabacloud_oss_v2.models import PutBucketRequest, PutObjectRequest
35
+ from alibabacloud_bailian20231229.client import Client as ModelstudioClient
36
+ from alibabacloud_tea_openapi import models as open_api_models
37
+ from alibabacloud_bailian20231229 import models as ModelstudioTypes
38
+ from alibabacloud_tea_util import models as util_models
39
+ except Exception:
40
+ oss = None
41
+ PutBucketRequest = None
42
+ PutObjectRequest = None
43
+ ModelstudioClient = None
44
+ open_api_models = None
45
+ ModelstudioTypes = None
46
+ util_models = None
47
+
48
+
49
+ class OSSConfig(BaseModel):
50
+ region: str = Field("cn-hangzhou", description="OSS region")
51
+ access_key_id: Optional[str] = None
52
+ access_key_secret: Optional[str] = None
53
+ bucket_prefix: str = Field(
54
+ "tmpbucket-agentscope-runtime",
55
+ description="Prefix for temporary buckets if creation is needed",
56
+ )
57
+
58
+ @classmethod
59
+ def from_env(cls) -> "OSSConfig":
60
+ return cls(
61
+ region=os.environ.get("OSS_REGION", "cn-hangzhou"),
62
+ access_key_id=os.environ.get(
63
+ "OSS_ACCESS_KEY_ID",
64
+ os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID"),
65
+ ),
66
+ access_key_secret=os.environ.get(
67
+ "OSS_ACCESS_KEY_SECRET",
68
+ os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
69
+ ),
70
+ )
71
+
72
+ def ensure_valid(self) -> None:
73
+ # allow fallback to Alibaba Cloud AK/SK via from_env()
74
+ if not self.access_key_id or not self.access_key_secret:
75
+ raise RuntimeError(
76
+ "Missing AccessKey for OSS. Set either OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET "
77
+ "or ALIBABA_CLOUD_ACCESS_KEY_ID/ALIBABA_CLOUD_ACCESS_KEY_SECRET.",
78
+ )
79
+
80
+
81
+ class ModelstudioConfig(BaseModel):
82
+ endpoint: str = Field(
83
+ "bailian.cn-beijing.aliyuncs.com",
84
+ description="Modelstudio service endpoint",
85
+ )
86
+ workspace_id: Optional[str] = None
87
+ access_key_id: Optional[str] = None
88
+ access_key_secret: Optional[str] = None
89
+ dashscope_api_key: Optional[str] = None
90
+
91
+ @classmethod
92
+ def from_env(cls) -> "ModelstudioConfig":
93
+ return cls(
94
+ endpoint=os.environ.get(
95
+ "MODELSTUDIO_ENDPOINT",
96
+ "bailian.cn-beijing.aliyuncs.com",
97
+ ),
98
+ workspace_id=os.environ.get("MODELSTUDIO_WORKSPACE_ID"),
99
+ access_key_id=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID"),
100
+ access_key_secret=os.environ.get(
101
+ "ALIBABA_CLOUD_ACCESS_KEY_SECRET",
102
+ ),
103
+ dashscope_api_key=os.environ.get(
104
+ "DASHSCOPE_API_KEY",
105
+ ),
106
+ )
107
+
108
+ def ensure_valid(self) -> None:
109
+ missing = []
110
+ if not self.workspace_id:
111
+ missing.append("MODELSTUDIO_WORKSPACE_ID")
112
+ if not self.access_key_id:
113
+ missing.append("ALIBABA_CLOUD_ACCESS_KEY_ID")
114
+ if not self.access_key_secret:
115
+ missing.append("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
116
+ if missing:
117
+ raise RuntimeError(
118
+ f"Missing required Modelstudio env vars: {', '.join(missing)}",
119
+ )
120
+
121
+
122
+ def _assert_cloud_sdks_available():
123
+ if oss is None or ModelstudioClient is None:
124
+ raise RuntimeError(
125
+ "Cloud SDKs not installed. Please install: "
126
+ "alibabacloud-oss-v2 alibabacloud-bailian20231229 "
127
+ "alibabacloud-credentials alibabacloud-tea-openapi alibabacloud-tea-util",
128
+ )
129
+
130
+
131
+ def _oss_get_client(oss_cfg: OSSConfig):
132
+ oss_cfg.ensure_valid()
133
+ # Ensure OSS SDK can read credentials from environment variables.
134
+ # If OSS_* are not set, populate them from resolved config (which may
135
+ # already have fallen back to ALIBABA_CLOUD_* as per from_env()).
136
+ if not os.environ.get("OSS_ACCESS_KEY_ID") and oss_cfg.access_key_id:
137
+ os.environ["OSS_ACCESS_KEY_ID"] = str(oss_cfg.access_key_id)
138
+ if (
139
+ not os.environ.get("OSS_ACCESS_KEY_SECRET")
140
+ and oss_cfg.access_key_secret
141
+ ):
142
+ os.environ["OSS_ACCESS_KEY_SECRET"] = str(oss_cfg.access_key_secret)
143
+
144
+ credentials_provider = (
145
+ oss.credentials.EnvironmentVariableCredentialsProvider()
146
+ )
147
+ cfg = oss.config.load_default()
148
+ cfg.credentials_provider = credentials_provider
149
+ cfg.region = oss_cfg.region
150
+ return oss.Client(cfg)
151
+
152
+
153
+ async def _oss_create_bucket_if_not_exists(client, bucket_name: str) -> None:
154
+ try:
155
+ exists = client.is_bucket_exist(bucket=bucket_name)
156
+ except Exception:
157
+ exists = False
158
+ if not exists:
159
+ req = PutBucketRequest(
160
+ bucket=bucket_name,
161
+ acl="private",
162
+ create_bucket_configuration=oss.CreateBucketConfiguration(
163
+ storage_class="IA",
164
+ ),
165
+ )
166
+ try:
167
+ put_bucket_result = client.put_bucket(req)
168
+ logger.info(
169
+ f"put bucket status code: {put_bucket_result.status_code},"
170
+ f" request id: {put_bucket_result.request_id}",
171
+ )
172
+ except oss.exceptions.OperationError as e:
173
+ logger.error(
174
+ "OSS PutBucket failed: Http Status: %s, ErrorCode: %s, RequestId: %s, Message: %s",
175
+ getattr(e, "http_code", None),
176
+ getattr(e, "error_code", None),
177
+ getattr(e, "request_id", None),
178
+ getattr(e, "message", str(e)),
179
+ )
180
+ raise
181
+ except Exception as e:
182
+ logger.error("Unexpected put bucket failure: %s", e, exc_info=True)
183
+ raise
184
+ result = client.put_bucket_tags(
185
+ oss.PutBucketTagsRequest(
186
+ bucket=bucket_name,
187
+ tagging=oss.Tagging(
188
+ tag_set=oss.TagSet(
189
+ tags=[
190
+ oss.Tag(
191
+ key="bailian-high-code-deploy-oss-access",
192
+ value="ReadAndAdd",
193
+ ),
194
+ ],
195
+ ),
196
+ ),
197
+ ),
198
+ )
199
+ logger.info(
200
+ f"put bucket tag status code: {result.status_code}, request id: {result.request_id}",
201
+ )
202
+
203
+
204
+ def _create_bucket_name(prefix: str, base_name: str) -> str:
205
+ import re as _re
206
+
207
+ ts = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
208
+ base = _re.sub(r"\s+", "-", base_name)
209
+ base = _re.sub(r"[^a-zA-Z0-9-]", "", base).lower().strip("-")
210
+ name = f"{prefix}-{base}-{ts}"
211
+ return name[:63]
212
+
213
+
214
+ async def _oss_put_and_presign(
215
+ client,
216
+ bucket_name: str,
217
+ object_key: str,
218
+ file_bytes: bytes,
219
+ ) -> str:
220
+ import datetime as _dt
221
+
222
+ put_req = PutObjectRequest(
223
+ bucket=bucket_name,
224
+ key=object_key,
225
+ body=file_bytes,
226
+ )
227
+ client.put_object(put_req)
228
+ pre = client.presign(
229
+ oss.GetObjectRequest(bucket=bucket_name, key=object_key),
230
+ expires=_dt.timedelta(minutes=180),
231
+ )
232
+ return pre.url
233
+
234
+
235
+ async def _modelstudio_deploy(
236
+ cfg: ModelstudioConfig,
237
+ file_url: str,
238
+ filename: str,
239
+ deploy_name: str,
240
+ agent_id: Optional[str] = None,
241
+ agent_desc: Optional[str] = None,
242
+ telemetry_enabled: bool = True,
243
+ ) -> str:
244
+ cfg.ensure_valid()
245
+ config = open_api_models.Config(
246
+ access_key_id=cfg.access_key_id,
247
+ access_key_secret=cfg.access_key_secret,
248
+ )
249
+ config.endpoint = cfg.endpoint
250
+ client_modelstudio = ModelstudioClient(config)
251
+ req = ModelstudioTypes.HighCodeDeployRequest(
252
+ agent_desc=agent_desc,
253
+ agent_id=agent_id,
254
+ source_code_name=filename,
255
+ source_code_oss_url=file_url,
256
+ agent_name=deploy_name,
257
+ telemetry_enabled=telemetry_enabled,
258
+ )
259
+ runtime = util_models.RuntimeOptions()
260
+ headers: Dict[str, str] = {}
261
+ resp = client_modelstudio.high_code_deploy_with_options(
262
+ cfg.workspace_id,
263
+ req,
264
+ headers,
265
+ runtime,
266
+ )
267
+
268
+ # logger.info(json.dumps(resp.to_map(), indent=2, ensure_ascii=False))
269
+ request_id = resp.to_map()["headers"].get("x-acs-request-id")
270
+ logger.info("deploy request id: %s", request_id)
271
+
272
+ # Extract deploy identifier string from response
273
+ def _extract_deploy_identifier(response_obj) -> str:
274
+ try:
275
+ if isinstance(response_obj, str):
276
+ return response_obj
277
+ # Tea responses often have a 'body' that can be a dict or model
278
+ body = getattr(response_obj, "body", None)
279
+
280
+ # 1) If body is a plain string
281
+ if isinstance(body, str):
282
+ return body
283
+ # 2) If body is a dict, prefer common fields
284
+ if isinstance(body, dict):
285
+ # Explicit error handling: do not build URL on failure
286
+ if isinstance(body.get("success"), bool) and not body.get(
287
+ "success",
288
+ ):
289
+ err_code = (
290
+ body.get("errorCode") or body.get("code") or "unknown"
291
+ )
292
+ err_msg = body.get("errorMsg") or body.get("message") or ""
293
+ raise RuntimeError(
294
+ f"ModelStudio deploy failed: {err_code} {err_msg}".strip(),
295
+ )
296
+ for key in ("data", "result", "deployId"):
297
+ val = body.get(key)
298
+ if isinstance(val, str) and val:
299
+ return val
300
+ # Try nested structures
301
+ data_val = body.get("data")
302
+ if isinstance(data_val, dict):
303
+ for key in ("id", "deployId"):
304
+ v = data_val.get(key)
305
+ if isinstance(v, str) and v:
306
+ return v
307
+ # 3) If body is a Tea model, try to_map()
308
+ if hasattr(body, "to_map") and callable(getattr(body, "to_map")):
309
+ try:
310
+ m = body.to_map()
311
+ if isinstance(m, dict):
312
+ if isinstance(m.get("success"), bool) and not m.get(
313
+ "success",
314
+ ):
315
+ err_code = (
316
+ m.get("errorCode")
317
+ or m.get("code")
318
+ or "unknown"
319
+ )
320
+ err_msg = (
321
+ m.get("errorMsg") or m.get("message") or ""
322
+ )
323
+ raise RuntimeError(
324
+ f"ModelStudio deploy failed: {err_code} {err_msg}".strip(),
325
+ )
326
+ for key in ("data", "result", "deployId"):
327
+ val = m.get(key)
328
+ if isinstance(val, str) and val:
329
+ return val
330
+ d = m.get("data")
331
+ if isinstance(d, dict):
332
+ for key in ("id", "deployId"):
333
+ v = d.get(key)
334
+ if isinstance(v, str) and v:
335
+ return v
336
+ except Exception:
337
+ raise
338
+ # 4) If response_obj itself is a dict
339
+ if isinstance(response_obj, dict):
340
+ b = response_obj.get("body")
341
+ if isinstance(b, dict):
342
+ if isinstance(b.get("success"), bool) and not b.get(
343
+ "success",
344
+ ):
345
+ err_code = (
346
+ b.get("errorCode") or b.get("code") or "unknown"
347
+ )
348
+ err_msg = b.get("errorMsg") or b.get("message") or ""
349
+ raise RuntimeError(
350
+ f"ModelStudio deploy failed: {err_code} {err_msg}".strip(),
351
+ )
352
+ for key in ("data", "result", "deployId"):
353
+ val = b.get(key)
354
+ if isinstance(val, str) and val:
355
+ return val
356
+ # Fallback: return empty to avoid polluting URL with dump
357
+ return ""
358
+ except Exception: # pragma: no cover - conservative fallback
359
+ # Propagate errors as empty identifier; upper layer logs/raises
360
+ raise
361
+
362
+ return _extract_deploy_identifier(resp)
363
+
364
+
365
+ class ModelstudioDeployManager(DeployManager):
366
+ """Deployer for Alibaba Modelstudio Function Compute based agent
367
+ deployment.
368
+
369
+ This deployer packages the user project into a wheel, uploads it to OSS,
370
+ and triggers a Modelstudio Full-Code deploy.
371
+ """
372
+
373
+ def __init__(
374
+ self,
375
+ oss_config: Optional[OSSConfig] = None,
376
+ modelstudio_config: Optional[ModelstudioConfig] = None,
377
+ build_root: Optional[Union[str, Path]] = None,
378
+ ) -> None:
379
+ super().__init__()
380
+ self.oss_config = oss_config or OSSConfig.from_env()
381
+ self.modelstudio_config = (
382
+ modelstudio_config or ModelstudioConfig.from_env()
383
+ )
384
+ self.build_root = Path(build_root) if build_root else None
385
+
386
+ async def _generate_wrapper_and_build_wheel(
387
+ self,
388
+ project_dir: Union[Optional[str], Path],
389
+ cmd: Optional[str] = None,
390
+ deploy_name: Optional[str] = None,
391
+ telemetry_enabled: bool = True,
392
+ ) -> Tuple[Path, str]:
393
+ """
394
+ 校验参数、生成 wrapper 项目并构建 wheel。
395
+
396
+ 返回: (wheel_path, wrapper_project_dir, name)
397
+ """
398
+ if not project_dir or not cmd:
399
+ raise ValueError(
400
+ "project_dir and cmd are required for "
401
+ "Modelstudio deployment",
402
+ )
403
+
404
+ project_dir = Path(project_dir).resolve()
405
+ if not project_dir.is_dir():
406
+ raise FileNotFoundError(f"Project dir not found: {project_dir}")
407
+
408
+ name = deploy_name or default_deploy_name()
409
+ proj_root = project_dir.resolve()
410
+ if isinstance(self.build_root, Path):
411
+ effective_build_root = self.build_root.resolve()
412
+ else:
413
+ if self.build_root:
414
+ effective_build_root = Path(self.build_root).resolve()
415
+ else:
416
+ effective_build_root = (
417
+ proj_root.parent / ".agentscope_runtime_builds"
418
+ ).resolve()
419
+
420
+ build_dir = effective_build_root / f"build-{int(time.time())}"
421
+ build_dir.mkdir(parents=True, exist_ok=True)
422
+
423
+ logger.info("Generating wrapper project for %s", name)
424
+ wrapper_project_dir, _ = await generate_wrapper_project(
425
+ build_root=build_dir,
426
+ user_project_dir=project_dir,
427
+ start_cmd=cmd,
428
+ deploy_name=name,
429
+ telemetry_enabled=telemetry_enabled,
430
+ )
431
+
432
+ logger.info("Building wheel under %s", wrapper_project_dir)
433
+ wheel_path = await build_wheel(wrapper_project_dir)
434
+ return wheel_path, name
435
+
436
+ def _generate_env_file(
437
+ self,
438
+ project_dir: Union[str, Path],
439
+ environment: Optional[Dict[str, str]] = None,
440
+ env_filename: str = ".env",
441
+ ) -> Optional[Path]:
442
+ """
443
+ Generate a .env file from environment variables dictionary.
444
+
445
+ Args:
446
+ project_dir: The project directory where the .env file will be
447
+ created environment: Dictionary of environment variables to
448
+ write to .env file env_filename: Name of the env file (default:
449
+ ".env")
450
+
451
+ Returns:
452
+ Path to the created .env file, or None if no environment
453
+ variables provided
454
+ """
455
+ if not environment:
456
+ return None
457
+
458
+ project_path = Path(project_dir).resolve()
459
+ if not project_path.exists():
460
+ raise FileNotFoundError(
461
+ f"Project directory not found: " f"{project_path}",
462
+ )
463
+
464
+ env_file_path = project_path / env_filename
465
+
466
+ try:
467
+ with env_file_path.open("w", encoding="utf-8") as f:
468
+ f.write("# Environment variables used by AgentScope Runtime\n")
469
+
470
+ for key, value in environment.items():
471
+ # Escape special characters and quote values if needed
472
+ if value is None:
473
+ continue
474
+
475
+ # Quote values that contain spaces or special characters
476
+ if " " in str(value) or any(
477
+ char in str(value)
478
+ for char in ["$", "`", '"', "'", "\\"]
479
+ ):
480
+ # Escape existing quotes and wrap in double quotes
481
+ escaped_value = (
482
+ str(value)
483
+ .replace("\\", "\\\\")
484
+ .replace('"', '\\"')
485
+ )
486
+ f.write(f'{key}="{escaped_value}"\n')
487
+ else:
488
+ f.write(f"{key}={value}\n")
489
+
490
+ logger.info(f"Generated .env file at: {env_file_path}")
491
+ return env_file_path
492
+
493
+ except Exception as e:
494
+ logger.warning(f"Failed to generate .env file: {e}")
495
+ return None
496
+
497
+ async def _upload_and_deploy(
498
+ self,
499
+ wheel_path: Path,
500
+ name: str,
501
+ agent_id: Optional[str] = None,
502
+ agent_desc: Optional[str] = None,
503
+ telemetry_enabled: bool = True,
504
+ ) -> Tuple[str, str, str]:
505
+ logger.info("Uploading wheel to OSS and generating presigned URL")
506
+ client = _oss_get_client(self.oss_config)
507
+
508
+ bucket_suffix = (
509
+ os.getenv("MODELSTUDIO_WORKSPACE_ID", str(uuid.uuid4()))
510
+ ).lower()
511
+ bucket_name = (f"tmp-code-deploy-" f"{bucket_suffix}")[:63]
512
+ await _oss_create_bucket_if_not_exists(client, bucket_name)
513
+ filename = wheel_path.name
514
+ with wheel_path.open("rb") as f:
515
+ file_bytes = f.read()
516
+ artifact_url = await _oss_put_and_presign(
517
+ client,
518
+ bucket_name,
519
+ filename,
520
+ file_bytes,
521
+ )
522
+
523
+ logger.info("Triggering Modelstudio Full-Code deploy for %s", name)
524
+ deploy_identifier = await _modelstudio_deploy(
525
+ agent_desc=agent_desc,
526
+ agent_id=agent_id,
527
+ cfg=self.modelstudio_config,
528
+ file_url=artifact_url,
529
+ filename=filename,
530
+ deploy_name=name,
531
+ telemetry_enabled=telemetry_enabled,
532
+ )
533
+
534
+ def _build_console_url(endpoint: str) -> str:
535
+ # Map API endpoint to console domain (no fragment in base)
536
+ base = (
537
+ "https://pre-bailian.console.aliyun.com/?tab=app#"
538
+ if ("bailian-pre" in endpoint or "pre" in endpoint)
539
+ else "https://bailian.console.aliyun.com/?tab=app#"
540
+ )
541
+ # Optional query can be appended if needed; keep path clean
542
+ return f"{base}/app-center"
543
+
544
+ console_url = (
545
+ _build_console_url(
546
+ self.modelstudio_config.endpoint,
547
+ )
548
+ if deploy_identifier
549
+ else ""
550
+ )
551
+ return artifact_url, console_url, deploy_identifier
552
+
553
+ async def deploy(
554
+ self,
555
+ runner: Optional[Runner] = None,
556
+ endpoint_path: str = "/process",
557
+ services_config: Optional[Union[ServicesConfig, dict]] = None,
558
+ protocol_adapters: Optional[list[ProtocolAdapter]] = None,
559
+ requirements: Optional[Union[str, List[str]]] = None,
560
+ extra_packages: Optional[List[str]] = None,
561
+ environment: Optional[Dict[str, str]] = None,
562
+ # runtime_config: Optional[Dict] = None,
563
+ # ModelStudio-specific/packaging args (required)
564
+ project_dir: Optional[Union[str, Path]] = None,
565
+ cmd: Optional[str] = None,
566
+ deploy_name: Optional[str] = None,
567
+ skip_upload: bool = False,
568
+ telemetry_enabled: bool = True,
569
+ external_whl_path: Optional[str] = None,
570
+ agent_id: Optional[str] = None,
571
+ agent_desc: Optional[str] = None,
572
+ **kwargs,
573
+ ) -> Dict[str, str]:
574
+ """
575
+ Package the project, upload to OSS and trigger ModelStudio deploy.
576
+
577
+ Returns a dict containing deploy_id, wheel_path, artifact_url (if uploaded),
578
+ resource_name (deploy_name), and workspace_id.
579
+ """
580
+ if not agent_id:
581
+ if not runner and not project_dir and not external_whl_path:
582
+ raise ValueError("")
583
+
584
+ # convert services_config to Model body
585
+ if services_config and isinstance(services_config, dict):
586
+ services_config = ServicesConfig(**services_config)
587
+
588
+ try:
589
+ if runner:
590
+ agent = runner._agent
591
+
592
+ # Create package project for detached deployment
593
+ project_dir = await LocalDeployManager.create_detached_project(
594
+ agent=agent,
595
+ endpoint_path=endpoint_path,
596
+ services_config=services_config, # type: ignore[arg-type]
597
+ protocol_adapters=protocol_adapters,
598
+ requirements=requirements,
599
+ extra_packages=extra_packages,
600
+ **kwargs,
601
+ )
602
+ if project_dir:
603
+ self._generate_env_file(project_dir, environment)
604
+ cmd = "python main.py"
605
+ deploy_name = deploy_name or default_deploy_name()
606
+
607
+ if agent_id:
608
+ if not external_whl_path:
609
+ raise FileNotFoundError(
610
+ "wheel file not found. "
611
+ "Please specify your .whl file path by "
612
+ "'--whl-path <whlpath>' in command line.",
613
+ )
614
+ # if whl exists then skip the project package method
615
+ if external_whl_path:
616
+ wheel_path = Path(external_whl_path).resolve()
617
+ if not wheel_path.is_file():
618
+ raise FileNotFoundError(
619
+ f"External wheel file not found: {wheel_path}",
620
+ )
621
+ name = deploy_name or default_deploy_name()
622
+ # 如果是更新agent,且没有传deploy_name, 则不更新名字
623
+ if agent_id and (deploy_name is None):
624
+ name = None
625
+ else:
626
+ (
627
+ wheel_path,
628
+ name,
629
+ ) = await self._generate_wrapper_and_build_wheel(
630
+ project_dir=project_dir,
631
+ cmd=cmd,
632
+ deploy_name=deploy_name,
633
+ telemetry_enabled=telemetry_enabled,
634
+ )
635
+
636
+ artifact_url = ""
637
+ console_url = ""
638
+ deploy_identifier = ""
639
+ if not skip_upload:
640
+ # Only require cloud SDKs and credentials when performing upload/deploy
641
+ _assert_cloud_sdks_available()
642
+ self.oss_config.ensure_valid()
643
+ self.modelstudio_config.ensure_valid()
644
+ (
645
+ artifact_url,
646
+ console_url,
647
+ deploy_identifier,
648
+ ) = await self._upload_and_deploy(
649
+ wheel_path,
650
+ name,
651
+ agent_id,
652
+ agent_desc,
653
+ telemetry_enabled,
654
+ )
655
+
656
+ result: Dict[str, str] = {
657
+ "wheel_path": str(wheel_path),
658
+ "artifact_url": artifact_url,
659
+ "resource_name": name,
660
+ "workspace_id": self.modelstudio_config.workspace_id or "",
661
+ "url": console_url,
662
+ }
663
+ if deploy_identifier:
664
+ result["deploy_id"] = deploy_identifier
665
+
666
+ return result
667
+ except Exception as e:
668
+ # Print richer error message to improve UX
669
+ err_text = str(e)
670
+ logger.error("Failed to deploy to modelstudio: %s", err_text)
671
+ raise
672
+
673
+ async def stop(self) -> None: # pragma: no cover - not supported yet
674
+ pass
675
+
676
+ def get_status(self) -> str: # pragma: no cover - not supported yet
677
+ return "unknown"
File without changes
@@ -0,0 +1,14 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Deployment modes and configuration for unified FastAPI architecture."""
3
+
4
+ from enum import Enum
5
+
6
+
7
+ class DeploymentMode(str, Enum):
8
+ """FastAPI application deployment modes."""
9
+
10
+ DAEMON_THREAD = "daemon_thread" # LocalDeployManager daemon thread mode
11
+ DETACHED_PROCESS = (
12
+ "detached_process" # LocalDeployManager detached process mode
13
+ )
14
+ STANDALONE = "standalone" # Package project template mode
@@ -0,0 +1,8 @@
1
+ # -*- coding: utf-8 -*-
2
+ from .runner_image_factory import RunnerImageFactory
3
+ from .docker_image_builder import (
4
+ RegistryConfig,
5
+ BuildConfig,
6
+ DockerImageBuilder,
7
+ )
8
+ from .dockerfile_generator import DockerfileConfig, DockerfileGenerator