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