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,306 @@
1
+ # -*- coding: utf-8 -*-
2
+ # pylint:disable=protected-access
3
+
4
+ import hashlib
5
+ import logging
6
+ import os
7
+ from typing import Optional, List, Dict, Union
8
+
9
+ from pydantic import BaseModel, Field
10
+
11
+ from agentscope_runtime.engine.runner import Runner
12
+
13
+ # from .package_project import PackageConfig, package_project, create_tar_gz
14
+ from ..package_project_utils import (
15
+ PackageConfig,
16
+ package_project,
17
+ )
18
+ from ..service_utils import (
19
+ ServicesConfig,
20
+ )
21
+ from .dockerfile_generator import DockerfileGenerator, DockerfileConfig
22
+ from .docker_image_builder import (
23
+ DockerImageBuilder,
24
+ BuildConfig,
25
+ RegistryConfig,
26
+ )
27
+
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ class RunnerImageConfig(BaseModel):
33
+ """Complete configuration for building a Runner image"""
34
+
35
+ # Package configuration
36
+ requirements: Optional[List[str]] = None
37
+ extra_packages: Optional[List[str]] = None
38
+ build_context_dir: str = "/tmp/k8s_build"
39
+ endpoint_path: str = "/process"
40
+ protocol_adapters: Optional[List] = None # New: protocol adapters
41
+ services_config: Optional[ServicesConfig] = None
42
+ custom_endpoints: Optional[
43
+ List[Dict]
44
+ ] = None # New: custom endpoints configuration
45
+
46
+ # Docker configuration
47
+ base_image: str = "python:3.10-slim-bookworm"
48
+ port: int = 8000
49
+ env_vars: Dict[str, str] = Field(default_factory=lambda: {})
50
+ startup_command: Optional[str] = None
51
+
52
+ # Build configuration
53
+ no_cache: bool = False
54
+ quiet: bool = False
55
+ build_args: Dict[str, str] = {}
56
+ platform: Optional[str] = None
57
+
58
+ # Image naming
59
+ image_name: Optional[str] = ("agent",)
60
+ image_tag: Optional[str] = None
61
+
62
+ # Registry configuration
63
+ registry_config: Optional[RegistryConfig] = None
64
+ push_to_registry: bool = False
65
+
66
+
67
+ class RunnerImageFactory:
68
+ """
69
+ Factory class for building Runner Docker images.
70
+ Coordinates ProjectPackager, DockerfileGenerator, and DockerImageBuilder.
71
+ """
72
+
73
+ def __init__(self):
74
+ """
75
+ Initialize the Runner image factory.
76
+ """
77
+ self.dockerfile_generator = DockerfileGenerator()
78
+ self.image_builder = DockerImageBuilder()
79
+
80
+ @staticmethod
81
+ def _generate_image_name(
82
+ runner: Runner,
83
+ config: RunnerImageConfig,
84
+ ) -> str:
85
+ """Generate a unique image tag based on runner content and config"""
86
+ # Create hash based on runner and configuration
87
+ if config.image_name:
88
+ return config.image_name
89
+ hash_content = (
90
+ f"{str(runner._agent.name)}"
91
+ f"{str(config.requirements)}"
92
+ f"{str(config.extra_files)}"
93
+ f"{config.base_image}"
94
+ f"{config.port}"
95
+ )
96
+ content_hash = hashlib.md5(hash_content.encode()).hexdigest()[:8]
97
+
98
+ return f"agent-{content_hash}"
99
+
100
+ @staticmethod
101
+ def _validate_runner(runner: Runner):
102
+ """Validate runner object"""
103
+ if not hasattr(runner, "_agent") or runner._agent is None:
104
+ raise ValueError("Runner must have a valid agent")
105
+
106
+ # Log warnings for missing components
107
+ if not hasattr(runner, "_environment_manager"):
108
+ logger.warning("Runner missing _environment_manager")
109
+ if not hasattr(runner, "_context_manager"):
110
+ logger.warning("Runner missing _context_manager")
111
+
112
+ @staticmethod
113
+ def _validate_requirements(
114
+ requirements: Optional[Union[str, List[str]]],
115
+ ) -> List[str]:
116
+ """Validate and normalize requirements"""
117
+ if requirements is None:
118
+ return []
119
+ elif isinstance(requirements, str):
120
+ if os.path.exists(requirements):
121
+ with open(requirements, "r", encoding="utf-8") as f:
122
+ return [
123
+ line.strip() for line in f.readlines() if line.strip()
124
+ ]
125
+ else:
126
+ return [requirements]
127
+ elif isinstance(requirements, list):
128
+ return requirements
129
+ else:
130
+ raise ValueError(
131
+ f"Invalid requirements type: {type(requirements)}",
132
+ )
133
+
134
+ def _build_runner_image(
135
+ self,
136
+ runner: Runner,
137
+ config: RunnerImageConfig,
138
+ ) -> str:
139
+ """
140
+ Build a complete Docker image for the Runner.
141
+
142
+ This method coordinates all steps:
143
+ 1. Package the runner project
144
+ 2. Generate Dockerfile
145
+ 3. Build Docker image
146
+ 4. Optionally push to registry
147
+
148
+ Args:
149
+ runner: Runner object containing agent and managers
150
+ config: Configuration for the image building process
151
+
152
+ Returns:
153
+ str: Full image name (with registry if pushed)
154
+
155
+ Raises:
156
+ ValueError: If runner or configuration is invalid
157
+ RuntimeError: If any step of the build process fails
158
+ """
159
+ try:
160
+ # Validation
161
+ self._validate_runner(runner)
162
+
163
+ logger.info(f"Building Runner image: {config.image_tag}")
164
+
165
+ # Generate Dockerfile
166
+ logger.info("Generating Dockerfile...")
167
+ dockerfile_config = DockerfileConfig(
168
+ base_image=config.base_image,
169
+ port=config.port,
170
+ env_vars=config.env_vars,
171
+ startup_command=config.startup_command,
172
+ )
173
+
174
+ dockerfile_path = self.dockerfile_generator.create_dockerfile(
175
+ dockerfile_config,
176
+ )
177
+ logger.info(f"Dockerfile created: {dockerfile_path}")
178
+
179
+ # Package the project
180
+ logger.info("Packaging Runner project...")
181
+ project_dir, is_updated = package_project(
182
+ agent=runner._agent,
183
+ config=PackageConfig(
184
+ requirements=config.requirements,
185
+ extra_packages=config.extra_packages,
186
+ output_dir=config.build_context_dir,
187
+ endpoint_path=config.endpoint_path,
188
+ protocol_adapters=config.protocol_adapters,
189
+ services_config=config.services_config,
190
+ custom_endpoints=config.custom_endpoints,
191
+ ),
192
+ dockerfile_path=dockerfile_path,
193
+ # caller_depth is no longer needed due to automatic
194
+ # stack search
195
+ )
196
+ logger.info(f"Project packaged: {project_dir}")
197
+
198
+ # Build Docker image
199
+ logger.info("Building Docker image...")
200
+ build_config = BuildConfig(
201
+ no_cache=config.no_cache,
202
+ quiet=config.quiet,
203
+ build_args=config.build_args,
204
+ source_updated=is_updated,
205
+ platform=config.platform,
206
+ )
207
+
208
+ if config.push_to_registry:
209
+ # Build and push to registry
210
+ full_image_name = self.image_builder.build_and_push(
211
+ build_context=project_dir,
212
+ image_name=self._generate_image_name(runner, config),
213
+ image_tag=config.image_tag,
214
+ build_config=build_config,
215
+ registry_config=config.registry_config,
216
+ source_updated=is_updated,
217
+ )
218
+ logger.info(f"Image built and pushed: {full_image_name}")
219
+ else:
220
+ # Just build locally
221
+ full_image_name = self.image_builder.build_image(
222
+ build_context=project_dir,
223
+ image_name=self._generate_image_name(runner, config),
224
+ image_tag=config.image_tag,
225
+ config=build_config,
226
+ source_updated=is_updated,
227
+ )
228
+ logger.info(f"Image built locally: {full_image_name}")
229
+
230
+ return full_image_name
231
+
232
+ except Exception as e:
233
+ logger.error(f"Failed to build Runner image: {e}")
234
+ raise RuntimeError(f"Runner image build failed: {e}") from e
235
+
236
+ finally:
237
+ # Cleanup temporary resources
238
+ self.cleanup()
239
+
240
+ def build_runner_image(
241
+ self,
242
+ runner: Runner,
243
+ requirements: Optional[Union[str, List[str]]] = None,
244
+ extra_packages: Optional[List[str]] = None,
245
+ base_image: str = "python:3.10-slim-bookworm",
246
+ image_name: str = "agent",
247
+ image_tag: Optional[str] = None,
248
+ registry_config: Optional[RegistryConfig] = None,
249
+ push_to_registry: bool = False,
250
+ services_config: Optional[ServicesConfig] = None,
251
+ protocol_adapters: Optional[List] = None, # New: protocol adapters
252
+ custom_endpoints: Optional[
253
+ List[Dict]
254
+ ] = None, # New parameter for custom endpoints
255
+ **kwargs,
256
+ ) -> str:
257
+ """
258
+ Simplified interface for building Runner images.
259
+
260
+ Args:
261
+ runner: Runner object
262
+ requirements: Python requirements
263
+ extra_packages: Additional files to include
264
+ base_image: Docker base image
265
+ image_name: Docker image name
266
+ image_tag: Optional image tag
267
+ registry_config: Optional registry config
268
+ push_to_registry: Whether to push to registry
269
+ services_config: Optional services config
270
+ protocol_adapters: Protocol adapters
271
+ custom_endpoints: Custom endpoints from agent app
272
+ **kwargs: Additional configuration options
273
+
274
+ Returns:
275
+ str: Built image name
276
+ """
277
+ config = RunnerImageConfig(
278
+ requirements=self._validate_requirements(requirements),
279
+ extra_packages=extra_packages or [],
280
+ base_image=base_image,
281
+ image_name=image_name,
282
+ image_tag=image_tag,
283
+ registry_config=registry_config,
284
+ push_to_registry=push_to_registry,
285
+ protocol_adapters=protocol_adapters,
286
+ services_config=services_config,
287
+ custom_endpoints=custom_endpoints,
288
+ **kwargs,
289
+ )
290
+
291
+ return self._build_runner_image(runner, config)
292
+
293
+ def cleanup(self):
294
+ """Clean up all temporary resources"""
295
+ try:
296
+ self.dockerfile_generator.cleanup()
297
+ except Exception as e:
298
+ logger.warning(f"Error during cleanup: {e}")
299
+
300
+ def __enter__(self):
301
+ """Context manager entry"""
302
+ return self
303
+
304
+ def __exit__(self, exc_type, exc_val, exc_tb):
305
+ """Context manager exit with cleanup"""
306
+ self.cleanup()