|
| 1 | +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. |
| 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 | +import json |
| 16 | + |
| 17 | +from google.adk.tools import ToolContext |
| 18 | + |
| 19 | +from veadk.config import getenv |
| 20 | +from veadk.utils.logger import get_logger |
| 21 | +from veadk.utils.volcengine_sign import ve_request |
| 22 | + |
| 23 | +logger = get_logger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +def run_code(code: str, language: str, tool_context: ToolContext) -> str: |
| 27 | + """Run code in a code sandbox and return the output. |
| 28 | +
|
| 29 | + Args: |
| 30 | + code (str): The code to run. |
| 31 | + language (str): The programming language of the code. Language must be one of the supported languages: python3. |
| 32 | +
|
| 33 | + Returns: |
| 34 | + str: The output of the code execution. |
| 35 | + """ |
| 36 | + |
| 37 | + tool_id = getenv("AGENTKIT_TOOL_ID") |
| 38 | + host = getenv("AGENTKIT_TOOL_HOST") # temporary host for code run tool |
| 39 | + session_id = tool_context._invocation_context.session.id |
| 40 | + |
| 41 | + logger.debug(f"Running code in language: {language}, session_id={session_id}") |
| 42 | + |
| 43 | + access_key = getenv("VOLCENGINE_ACCESS_KEY") |
| 44 | + secret_key = getenv("VOLCENGINE_SECRET_KEY") |
| 45 | + |
| 46 | + res = ve_request( |
| 47 | + request_body={ |
| 48 | + "ToolId": tool_id, |
| 49 | + "UserSessionId": session_id, |
| 50 | + "OperationType": "RunCode", |
| 51 | + "OperationPayload": json.dumps( |
| 52 | + { |
| 53 | + "code": code, |
| 54 | + "timeout": 30, |
| 55 | + "kernel_name": language, |
| 56 | + } |
| 57 | + ), |
| 58 | + }, |
| 59 | + action="InvokeTool", |
| 60 | + ak=access_key, |
| 61 | + sk=secret_key, |
| 62 | + service="agentkit_stg", |
| 63 | + version="2025-10-30", |
| 64 | + region="cn-beijing", |
| 65 | + host=host, |
| 66 | + ) |
| 67 | + |
| 68 | + logger.debug(f"Invoke run code response: {res}") |
| 69 | + |
| 70 | + try: |
| 71 | + return res["Result"]["Result"] |
| 72 | + except KeyError as e: |
| 73 | + logger.error(f"Error occurred while running code: {e}, response is {res}") |
| 74 | + return res |
0 commit comments