agentscope-runtime 0.1.6__py3-none-any.whl → 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.
Files changed (87) hide show
  1. agentscope_runtime/common/container_clients/__init__.py +0 -0
  2. agentscope_runtime/{sandbox/manager → common}/container_clients/kubernetes_client.py +546 -6
  3. agentscope_runtime/engine/__init__.py +12 -0
  4. agentscope_runtime/engine/agents/agentscope_agent.py +130 -10
  5. agentscope_runtime/engine/agents/agno_agent.py +8 -10
  6. agentscope_runtime/engine/agents/langgraph_agent.py +52 -9
  7. agentscope_runtime/engine/app/__init__.py +6 -0
  8. agentscope_runtime/engine/app/agent_app.py +239 -0
  9. agentscope_runtime/engine/app/base_app.py +181 -0
  10. agentscope_runtime/engine/app/celery_mixin.py +92 -0
  11. agentscope_runtime/engine/deployers/__init__.py +13 -0
  12. agentscope_runtime/engine/deployers/adapter/responses/__init__.py +0 -0
  13. agentscope_runtime/engine/deployers/adapter/responses/response_api_adapter_utils.py +2890 -0
  14. agentscope_runtime/engine/deployers/adapter/responses/response_api_agent_adapter.py +51 -0
  15. agentscope_runtime/engine/deployers/adapter/responses/response_api_protocol_adapter.py +314 -0
  16. agentscope_runtime/engine/deployers/base.py +1 -0
  17. agentscope_runtime/engine/deployers/cli_fc_deploy.py +203 -0
  18. agentscope_runtime/engine/deployers/kubernetes_deployer.py +272 -0
  19. agentscope_runtime/engine/deployers/local_deployer.py +414 -501
  20. agentscope_runtime/engine/deployers/modelstudio_deployer.py +838 -0
  21. agentscope_runtime/engine/deployers/utils/__init__.py +0 -0
  22. agentscope_runtime/engine/deployers/utils/deployment_modes.py +14 -0
  23. agentscope_runtime/engine/deployers/utils/docker_image_utils/__init__.py +8 -0
  24. agentscope_runtime/engine/deployers/utils/docker_image_utils/docker_image_builder.py +429 -0
  25. agentscope_runtime/engine/deployers/utils/docker_image_utils/dockerfile_generator.py +240 -0
  26. agentscope_runtime/engine/deployers/utils/docker_image_utils/runner_image_factory.py +306 -0
  27. agentscope_runtime/engine/deployers/utils/package_project_utils.py +1163 -0
  28. agentscope_runtime/engine/deployers/utils/service_utils/__init__.py +9 -0
  29. agentscope_runtime/engine/deployers/utils/service_utils/fastapi_factory.py +1064 -0
  30. agentscope_runtime/engine/deployers/utils/service_utils/fastapi_templates.py +157 -0
  31. agentscope_runtime/engine/deployers/utils/service_utils/process_manager.py +268 -0
  32. agentscope_runtime/engine/deployers/utils/service_utils/service_config.py +75 -0
  33. agentscope_runtime/engine/deployers/utils/service_utils/service_factory.py +220 -0
  34. agentscope_runtime/engine/deployers/utils/service_utils/standalone_main.py.j2 +211 -0
  35. agentscope_runtime/engine/deployers/utils/wheel_packager.py +389 -0
  36. agentscope_runtime/engine/helpers/agent_api_builder.py +651 -0
  37. agentscope_runtime/engine/runner.py +76 -35
  38. agentscope_runtime/engine/schemas/agent_schemas.py +112 -2
  39. agentscope_runtime/engine/schemas/embedding.py +37 -0
  40. agentscope_runtime/engine/schemas/modelstudio_llm.py +310 -0
  41. agentscope_runtime/engine/schemas/oai_llm.py +538 -0
  42. agentscope_runtime/engine/schemas/realtime.py +254 -0
  43. agentscope_runtime/engine/services/tablestore_memory_service.py +4 -1
  44. agentscope_runtime/engine/tracing/__init__.py +9 -3
  45. agentscope_runtime/engine/tracing/asyncio_util.py +24 -0
  46. agentscope_runtime/engine/tracing/base.py +66 -34
  47. agentscope_runtime/engine/tracing/local_logging_handler.py +45 -31
  48. agentscope_runtime/engine/tracing/message_util.py +528 -0
  49. agentscope_runtime/engine/tracing/tracing_metric.py +20 -8
  50. agentscope_runtime/engine/tracing/tracing_util.py +130 -0
  51. agentscope_runtime/engine/tracing/wrapper.py +794 -169
  52. agentscope_runtime/sandbox/box/base/base_sandbox.py +2 -1
  53. agentscope_runtime/sandbox/box/browser/browser_sandbox.py +2 -1
  54. agentscope_runtime/sandbox/box/dummy/dummy_sandbox.py +2 -1
  55. agentscope_runtime/sandbox/box/filesystem/filesystem_sandbox.py +2 -1
  56. agentscope_runtime/sandbox/box/gui/gui_sandbox.py +2 -1
  57. agentscope_runtime/sandbox/box/training_box/training_box.py +0 -42
  58. agentscope_runtime/sandbox/client/http_client.py +52 -18
  59. agentscope_runtime/sandbox/constant.py +3 -0
  60. agentscope_runtime/sandbox/custom/custom_sandbox.py +2 -1
  61. agentscope_runtime/sandbox/custom/example.py +2 -1
  62. agentscope_runtime/sandbox/enums.py +0 -1
  63. agentscope_runtime/sandbox/manager/sandbox_manager.py +29 -22
  64. agentscope_runtime/sandbox/model/container.py +6 -0
  65. agentscope_runtime/sandbox/registry.py +1 -1
  66. agentscope_runtime/sandbox/tools/tool.py +4 -0
  67. agentscope_runtime/version.py +1 -1
  68. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/METADATA +103 -59
  69. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/RECORD +87 -52
  70. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/entry_points.txt +1 -0
  71. /agentscope_runtime/{sandbox/manager/container_clients → common}/__init__.py +0 -0
  72. /agentscope_runtime/{sandbox/manager → common}/collections/__init__.py +0 -0
  73. /agentscope_runtime/{sandbox/manager → common}/collections/base_mapping.py +0 -0
  74. /agentscope_runtime/{sandbox/manager → common}/collections/base_queue.py +0 -0
  75. /agentscope_runtime/{sandbox/manager → common}/collections/base_set.py +0 -0
  76. /agentscope_runtime/{sandbox/manager → common}/collections/in_memory_mapping.py +0 -0
  77. /agentscope_runtime/{sandbox/manager → common}/collections/in_memory_queue.py +0 -0
  78. /agentscope_runtime/{sandbox/manager → common}/collections/in_memory_set.py +0 -0
  79. /agentscope_runtime/{sandbox/manager → common}/collections/redis_mapping.py +0 -0
  80. /agentscope_runtime/{sandbox/manager → common}/collections/redis_queue.py +0 -0
  81. /agentscope_runtime/{sandbox/manager → common}/collections/redis_set.py +0 -0
  82. /agentscope_runtime/{sandbox/manager → common}/container_clients/agentrun_client.py +0 -0
  83. /agentscope_runtime/{sandbox/manager → common}/container_clients/base_client.py +0 -0
  84. /agentscope_runtime/{sandbox/manager → common}/container_clients/docker_client.py +0 -0
  85. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/WHEEL +0 -0
  86. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/licenses/LICENSE +0 -0
  87. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,272 @@
1
+ # -*- coding: utf-8 -*-
2
+ import logging
3
+ import os
4
+ import time
5
+ from typing import Optional, Dict, List, Union, Any
6
+
7
+ from pydantic import BaseModel, Field
8
+
9
+ from .adapter.protocol_adapter import ProtocolAdapter
10
+ from .base import DeployManager
11
+ from .utils.docker_image_utils import (
12
+ RunnerImageFactory,
13
+ RegistryConfig,
14
+ )
15
+ from .utils.service_utils import (
16
+ ServicesConfig,
17
+ )
18
+ from ..runner import Runner
19
+ from ...common.container_clients.kubernetes_client import (
20
+ KubernetesClient,
21
+ )
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class K8sConfig(BaseModel):
27
+ # Kubernetes settings
28
+ k8s_namespace: Optional[str] = Field(
29
+ "agentscope-runtime",
30
+ description="Kubernetes namespace to deploy pods. Required if "
31
+ "container_deployment is 'k8s'.",
32
+ )
33
+ kubeconfig_path: Optional[str] = Field(
34
+ None,
35
+ description="Path to kubeconfig file. If not set, will try "
36
+ "in-cluster config or default kubeconfig.",
37
+ )
38
+
39
+
40
+ class BuildConfig(BaseModel):
41
+ """Build configuration"""
42
+
43
+ build_context_dir: str = "/tmp/k8s_build"
44
+ dockerfile_template: str = None
45
+ build_timeout: int = 600 # 10 minutes
46
+ push_timeout: int = 300 # 5 minutes
47
+ cleanup_after_build: bool = True
48
+
49
+
50
+ class KubernetesDeployManager(DeployManager):
51
+ """Kubernetes deployer for agent services"""
52
+
53
+ def __init__(
54
+ self,
55
+ kube_config: K8sConfig = None,
56
+ registry_config: RegistryConfig = RegistryConfig(),
57
+ use_deployment: bool = True,
58
+ build_context_dir: str = "/tmp/k8s_build",
59
+ ):
60
+ super().__init__()
61
+ self.kubeconfig = kube_config
62
+ self.registry_config = registry_config
63
+ self.image_factory = RunnerImageFactory()
64
+ self.use_deployment = use_deployment
65
+ self.build_context_dir = build_context_dir
66
+ self._deployed_resources = {}
67
+ self._built_images = {}
68
+
69
+ self.k8s_client = KubernetesClient(
70
+ config=self.kubeconfig,
71
+ image_registry=self.registry_config.get_full_url(),
72
+ )
73
+
74
+ async def deploy(
75
+ self,
76
+ runner: Runner,
77
+ endpoint_path: str = "/process",
78
+ stream: bool = True,
79
+ services_config: Optional[Union[ServicesConfig, dict]] = None,
80
+ custom_endpoints: Optional[List[Dict]] = None,
81
+ protocol_adapters: Optional[list[ProtocolAdapter]] = None,
82
+ requirements: Optional[Union[str, List[str]]] = None,
83
+ extra_packages: Optional[List[str]] = None,
84
+ base_image: str = "python:3.9-slim",
85
+ environment: Dict = None,
86
+ runtime_config: Dict = None,
87
+ port: int = 8090,
88
+ replicas: int = 1,
89
+ mount_dir: str = None,
90
+ image_name: str = "agent_llm",
91
+ image_tag: str = "latest",
92
+ push_to_registry: bool = False,
93
+ **kwargs,
94
+ ) -> Dict[str, Any]:
95
+ """
96
+ Deploy runner to Kubernetes.
97
+
98
+ Args:
99
+ runner: Complete Runner object with agent, environment_manager,
100
+ context_manager
101
+ endpoint_path: API endpoint path
102
+ stream: Enable streaming responses
103
+ services_config: Services configuration for context manager
104
+ custom_endpoints: Custom endpoints from agent app
105
+ protocol_adapters: protocol adapters
106
+ requirements: PyPI dependencies (following _agent_engines.py
107
+ pattern)
108
+ extra_packages: User code directory/file path
109
+ base_image: Docker base image
110
+ port: Container port
111
+ replicas: Number of replicas
112
+ environment: Environment variables dict
113
+ mount_dir: Mount directory
114
+ runtime_config: K8s runtime configuration
115
+ # Backward compatibility
116
+ image_name: Image name
117
+ image_tag: Image tag
118
+ push_to_registry: Push to registry
119
+ **kwargs: Additional arguments
120
+
121
+ Returns:
122
+ Dict containing deploy_id, url, resource_name, replicas
123
+
124
+ Raises:
125
+ RuntimeError: If deployment fails
126
+ """
127
+ created_resources = []
128
+ deploy_id = self.deploy_id
129
+
130
+ try:
131
+ logger.info(f"Starting deployment {deploy_id}")
132
+
133
+ # Handle backward compatibility
134
+ if runner is None:
135
+ raise ValueError(
136
+ "Runner must be provided",
137
+ )
138
+
139
+ # convert services_config to Model body
140
+ if services_config and isinstance(services_config, dict):
141
+ services_config = ServicesConfig(**services_config)
142
+
143
+ # Step 1: Build image with proper error handling
144
+ logger.info("Building runner image...")
145
+ try:
146
+ built_image_name = self.image_factory.build_runner_image(
147
+ runner=runner,
148
+ requirements=requirements,
149
+ extra_packages=extra_packages or [],
150
+ base_image=base_image,
151
+ stream=stream,
152
+ endpoint_path=endpoint_path,
153
+ build_context_dir=self.build_context_dir,
154
+ registry_config=self.registry_config,
155
+ image_name=image_name,
156
+ image_tag=image_tag,
157
+ push_to_registry=push_to_registry,
158
+ port=port,
159
+ services_config=services_config, # type: ignore[arg-type]
160
+ protocol_adapters=protocol_adapters,
161
+ custom_endpoints=custom_endpoints,
162
+ **kwargs,
163
+ )
164
+ if not built_image_name:
165
+ raise RuntimeError(
166
+ "Image build failed - no image name returned",
167
+ )
168
+
169
+ created_resources.append(f"image:{built_image_name}")
170
+ self._built_images[deploy_id] = built_image_name
171
+ logger.info(f"Image built successfully: {built_image_name}")
172
+ except Exception as e:
173
+ logger.error(f"Image build failed: {e}")
174
+ raise RuntimeError(f"Failed to build image: {e}") from e
175
+
176
+ if mount_dir:
177
+ if not os.path.isabs(mount_dir):
178
+ mount_dir = os.path.abspath(mount_dir)
179
+
180
+ if mount_dir:
181
+ volume_bindings = {
182
+ mount_dir: {
183
+ "bind": mount_dir,
184
+ "mode": "rw",
185
+ },
186
+ }
187
+ else:
188
+ volume_bindings = {}
189
+
190
+ resource_name = f"agent-{deploy_id[:8]}"
191
+
192
+ # Create Deployment
193
+ _id, ports, ip = self.k8s_client.create_deployment(
194
+ image=built_image_name,
195
+ name=resource_name,
196
+ ports=[port],
197
+ volumes=volume_bindings,
198
+ environment=environment,
199
+ runtime_config=runtime_config or {},
200
+ replicas=replicas,
201
+ create_service=True,
202
+ )
203
+ if not _id:
204
+ import traceback
205
+
206
+ raise RuntimeError(
207
+ f"Failed to create resource: "
208
+ f"{resource_name}, {traceback.format_exc()}",
209
+ )
210
+
211
+ if ports:
212
+ url = f"http://{ip}:{ports[0]}"
213
+ else:
214
+ url = f"http://{ip}:8080"
215
+
216
+ logger.info(f"Deployment {deploy_id} successful: {url}")
217
+
218
+ self._deployed_resources[deploy_id] = {
219
+ "resource_name": resource_name,
220
+ "service_name": _id,
221
+ "image": built_image_name,
222
+ "created_at": time.time(),
223
+ "replicas": replicas if self.use_deployment else 1,
224
+ "config": {
225
+ "runner": runner.__class__.__name__,
226
+ "extra_packages": extra_packages,
227
+ "requirements": requirements, # New format
228
+ "base_image": base_image,
229
+ "port": port,
230
+ "replicas": replicas,
231
+ "environment": environment,
232
+ "runtime_config": runtime_config,
233
+ "endpoint_path": endpoint_path,
234
+ "stream": stream,
235
+ "protocol_adapters": protocol_adapters,
236
+ **kwargs,
237
+ },
238
+ }
239
+ return {
240
+ "deploy_id": deploy_id,
241
+ "url": url,
242
+ "resource_name": resource_name,
243
+ "replicas": replicas,
244
+ }
245
+
246
+ except Exception as e:
247
+ import traceback
248
+
249
+ logger.error(f"Deployment {deploy_id} failed: {e}")
250
+ # Enhanced rollback with better error handling
251
+ raise RuntimeError(
252
+ f"Deployment failed: {e}, {traceback.format_exc()}",
253
+ ) from e
254
+
255
+ async def stop(self) -> bool:
256
+ """Stop service"""
257
+ if self.deploy_id not in self._deployed_resources:
258
+ return False
259
+
260
+ resources = self._deployed_resources[self.deploy_id]
261
+ service_name = resources["service_name"]
262
+ return self.k8s_client.remove_deployment(service_name)
263
+
264
+ def get_status(self) -> str:
265
+ """Get deployment status"""
266
+ if self.deploy_id not in self._deployed_resources:
267
+ return "not_found"
268
+
269
+ resources = self._deployed_resources[self.deploy_id]
270
+ service_name = resources["service_name"]
271
+
272
+ return self.k8s_client.get_deployment_status(service_name)