write_file.py
1 # Copyright (c) 2024-2026 Tencent Zhuque Lab. All rights reserved. 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 # Requirement: Any integration or derivative work must explicitly attribute 16 # Tencent Zhuque Lab (https://github.com/Tencent/AI-Infra-Guard) in its 17 # documentation or user interface, as detailed in the NOTICE file. 18 19 import os 20 from typing import Any 21 22 from utils.loging import logger 23 from utils.tool_context import ToolContext 24 25 26 # @register_tool 27 def write_file(file_path: str, content: str, context: ToolContext = None) -> dict[str, Any]: 28 """写入文件内容(会覆盖已有文件) 29 30 Args: 31 file_path: 文件路径 32 content: 要写入的内容 33 34 Returns: 35 包含成功状态和消息的字典 36 """ 37 try: 38 # 创建目录(如果不存在) 39 directory = os.path.dirname(file_path) 40 if not directory.startswith(context.folder): 41 return {"success": False, "message": f"Path is not allowed: {file_path}"} 42 if directory and not os.path.exists(directory): 43 os.makedirs(directory, exist_ok=True) 44 logger.info(f"Created directory: {directory}") 45 46 with open(file_path, "w", encoding="utf-8") as f: 47 f.write(content) 48 49 logger.info(f"Wrote file: {file_path} ({len(content)} chars)") 50 51 return { 52 "success": True, 53 "message": f"Successfully wrote {len(content)} characters to {file_path}", 54 } 55 56 except PermissionError: 57 return { 58 "success": False, 59 "message": f"Permission denied: {file_path}", 60 } 61 except Exception as e: 62 logger.error(f"Error writing file {file_path}: {e}") 63 return { 64 "success": False, 65 "message": f"Error writing file: {str(e)}", 66 }