|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import json |
| 18 | +import logging |
| 19 | +import mimetypes |
| 20 | +import re |
| 21 | +from typing import Optional |
| 22 | + |
| 23 | +from typing_extensions import override |
| 24 | +import vertexai |
| 25 | +from vertexai import types |
| 26 | + |
| 27 | +from ..agents.invocation_context import InvocationContext |
| 28 | +from ..utils.feature_decorator import experimental |
| 29 | +from .base_code_executor import BaseCodeExecutor |
| 30 | +from .code_execution_utils import CodeExecutionInput |
| 31 | +from .code_execution_utils import CodeExecutionResult |
| 32 | +from .code_execution_utils import File |
| 33 | + |
| 34 | +logger = logging.getLogger('google_adk.' + __name__) |
| 35 | + |
| 36 | + |
| 37 | +@experimental |
| 38 | +class AgentEngineSandboxCodeExecutor(BaseCodeExecutor): |
| 39 | + """A code executor that uses Agent Engine Code Execution Sandbox to execute code. |
| 40 | +
|
| 41 | + Attributes: |
| 42 | + sandbox_resource_name: If set, load the existing resource name of the code |
| 43 | + interpreter extension instead of creating a new one. Format: |
| 44 | + projects/123/locations/us-central1/reasoningEngines/456/sandboxEnvironments/789 |
| 45 | + """ |
| 46 | + |
| 47 | + sandbox_resource_name: str = None |
| 48 | + |
| 49 | + def __init__( |
| 50 | + self, |
| 51 | + sandbox_resource_name: Optional[str] = None, |
| 52 | + agent_engine_resource_name: Optional[str] = None, |
| 53 | + **data, |
| 54 | + ): |
| 55 | + """Initializes the AgentEngineSandboxCodeExecutor. |
| 56 | +
|
| 57 | + Args: |
| 58 | + sandbox_resource_name: If set, load the existing resource name of code |
| 59 | + execution sandbox, if not set, create a new one. Format: |
| 60 | + projects/123/locations/us-central1/reasoningEngines/456/ |
| 61 | + sandboxEnvironments/789 |
| 62 | + agent_engine_resource_name: The resource name of the agent engine to use |
| 63 | + to create the code execution sandbox. Format: |
| 64 | + projects/123/locations/us-central1/reasoningEngines/456, when both |
| 65 | + sandbox_resource_name and agent_engine_resource_name are set, |
| 66 | + agent_engine_resource_name will be ignored. |
| 67 | + **data: Additional keyword arguments to be passed to the base class. |
| 68 | + """ |
| 69 | + super().__init__(**data) |
| 70 | + sandbox_resource_name_pattern = r'^projects/([a-zA-Z0-9-_]+)/locations/([a-zA-Z0-9-_]+)/reasoningEngines/(\d+)/sandboxEnvironments/(\d+)$' |
| 71 | + agent_engine_resource_name_pattern = r'^projects/([a-zA-Z0-9-_]+)/locations/([a-zA-Z0-9-_]+)/reasoningEngines/(\d+)$' |
| 72 | + |
| 73 | + if sandbox_resource_name is not None: |
| 74 | + self.sandbox_resource_name = sandbox_resource_name |
| 75 | + self._project_id, self._location = ( |
| 76 | + self._get_project_id_and_location_from_resource_name( |
| 77 | + sandbox_resource_name, sandbox_resource_name_pattern |
| 78 | + ) |
| 79 | + ) |
| 80 | + elif agent_engine_resource_name is not None: |
| 81 | + self._project_id, self._location = ( |
| 82 | + self._get_project_id_and_location_from_resource_name( |
| 83 | + agent_engine_resource_name, agent_engine_resource_name_pattern |
| 84 | + ) |
| 85 | + ) |
| 86 | + # @TODO - Add TTL for sandbox creation after it is available |
| 87 | + # in SDK. |
| 88 | + operation = self._get_api_client().agent_engines.sandboxes.create( |
| 89 | + spec={'code_execution_environment': {}}, |
| 90 | + name=agent_engine_resource_name, |
| 91 | + config=types.CreateAgentEngineSandboxConfig( |
| 92 | + display_name='default_sandbox' |
| 93 | + ), |
| 94 | + ) |
| 95 | + self.sandbox_resource_name = operation.response.name |
| 96 | + else: |
| 97 | + raise ValueError( |
| 98 | + 'Either sandbox_resource_name or agent_engine_resource_name must be' |
| 99 | + ' set.' |
| 100 | + ) |
| 101 | + |
| 102 | + @override |
| 103 | + def execute_code( |
| 104 | + self, |
| 105 | + invocation_context: InvocationContext, |
| 106 | + code_execution_input: CodeExecutionInput, |
| 107 | + ) -> CodeExecutionResult: |
| 108 | + # Execute the code. |
| 109 | + input_data = { |
| 110 | + 'code': code_execution_input.code, |
| 111 | + } |
| 112 | + if code_execution_input.input_files: |
| 113 | + input_data['files'] = [ |
| 114 | + { |
| 115 | + 'name': f.name, |
| 116 | + 'contents': f.content, |
| 117 | + 'mimeType': f.mime_type, |
| 118 | + } |
| 119 | + for f in code_execution_input.input_files |
| 120 | + ] |
| 121 | + |
| 122 | + code_execution_response = ( |
| 123 | + self._get_api_client().agent_engines.sandboxes.execute_code( |
| 124 | + name=self.sandbox_resource_name, |
| 125 | + input_data=input_data, |
| 126 | + ) |
| 127 | + ) |
| 128 | + saved_files = [] |
| 129 | + stdout = '' |
| 130 | + stderr = '' |
| 131 | + for output in code_execution_response.outputs: |
| 132 | + if output.mime_type == 'application/json' and ( |
| 133 | + output.metadata is None |
| 134 | + or output.metadata.attributes is None |
| 135 | + or 'file_name' not in output.metadata.attributes |
| 136 | + ): |
| 137 | + json_output_data = json.loads(output.data.decode('utf-8')) |
| 138 | + stdout = json_output_data.get('stdout', '') |
| 139 | + stderr = json_output_data.get('stderr', '') |
| 140 | + else: |
| 141 | + file_name = '' |
| 142 | + if ( |
| 143 | + output.metadata is not None |
| 144 | + and output.metadata.attributes is not None |
| 145 | + ): |
| 146 | + file_name = output.metadata.attributes.get('file_name', b'').decode( |
| 147 | + 'utf-8' |
| 148 | + ) |
| 149 | + mime_type = output.mime_type |
| 150 | + if not mime_type: |
| 151 | + mime_type, _ = mimetypes.guess_type(file_name) |
| 152 | + saved_files.append( |
| 153 | + File( |
| 154 | + name=file_name, |
| 155 | + content=output.data, |
| 156 | + mime_type=mime_type, |
| 157 | + ) |
| 158 | + ) |
| 159 | + |
| 160 | + # Collect the final result. |
| 161 | + return CodeExecutionResult( |
| 162 | + stdout=stdout, |
| 163 | + stderr=stderr, |
| 164 | + output_files=saved_files, |
| 165 | + ) |
| 166 | + |
| 167 | + def _get_api_client(self): |
| 168 | + """Instantiates an API client for the given project and location. |
| 169 | +
|
| 170 | + It needs to be instantiated inside each request so that the event loop |
| 171 | + management can be properly propagated. |
| 172 | +
|
| 173 | + Returns: |
| 174 | + An API client for the given project and location. |
| 175 | + """ |
| 176 | + return vertexai.Client(project=self._project_id, location=self._location) |
| 177 | + |
| 178 | + def _get_project_id_and_location_from_resource_name( |
| 179 | + self, resource_name: str, pattern: str |
| 180 | + ) -> tuple[str, str]: |
| 181 | + """Extracts the project ID and location from the resource name.""" |
| 182 | + match = re.fullmatch(pattern, resource_name) |
| 183 | + |
| 184 | + if not match: |
| 185 | + raise ValueError(f'resource name {resource_name} is not valid.') |
| 186 | + |
| 187 | + return match.groups()[0], match.groups()[1] |
0 commit comments