# E:\AI_System\agent\model_manager.py
import os
import logging
try:
from agent.models.base_model import BaseModel # 作为模块导入
except ImportError:
# 直接运行时使用相对路径
from models.base_model import BaseModel
class ModelManager:
"""模型管理器 - 负责加载和管理AI模型"""
def __init__(self, model_dir="models", device="cpu", default_model=None):
"""
初始化模型管理器
:param model_dir: 模型存储目录
:param device: 运行设备 (cpu, cuda, mps)
:param default_model: 默认加载的模型名称
"""
self.logger = logging.getLogger('ModelManager')
self._setup_logger()
self.device = device
self.model_dir = model_dir
self.default_model = default_model
self.language_model = None
self.loaded_models = {}
self.log(f"📦 初始化模型管理器 | 设备: {device} | 模型目录: {model_dir} | 默认模型: {default_model}")
# 如果指定了默认模型,则自动加载
if default_model:
self.load_core_language_model(default_model)
def _setup_logger(self):
"""配置日志记录器"""
if not self.logger.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
self.logger.setLevel(logging.INFO)
self.logger.propagate = False
def log(self, message, level="info"):
"""记录日志"""
log_levels = {
"debug": self.logger.debug,
"info": self.logger.info,
"warning": self.logger.warning,
"error": self.logger.error
}
log_func = log_levels.get(level.lower(), self.logger.info)
log_func(message)
def load_core_language_model(self, model_name="minimal-model"):
"""加载核心语言模型"""
self.log(f"正在加载核心语言模型: {model_name}")
try:
# 简化实现 - 实际项目中会加载真实模型
self.language_model = BaseModel(model_name, "v1")
self.loaded_models[model_name] = self.language_model
self.log(f"✅ {model_name}-v1 加载成功")
return True
except Exception as e:
self.log(f"❌ 加载模型失败: {str(e)}", "error")
return False
def get_model(self, model_name):
"""获取指定模型"""
return self.loaded_models.get(model_name)
def get_loaded_models(self):
"""获取所有已加载模型"""
return list(self.loaded_models.values())
def get_current_model_info(self):
"""获取当前模型信息"""
if self.language_model:
return {
"name": self.language_model.name,
"version": self.language_model.version,
"status": "active"
}
return {"status": "no_model_loaded"}
def select_model(self, input_text, attitude_weight, complexity_level, user_preferences):
"""
选择最适合的模型(简化版)
:param input_text: 用户输入文本
:param attitude_weight: 态度权重
:param complexity_level: 复杂度级别
:param user_preferences: 用户偏好
:return: 选择的模型实例
"""
# 简化实现:总是返回核心语言模型
self.log(f"📊 选择模型 | 输入: '{input_text}' | 态度权重: {attitude_weight} | 复杂度: {complexity_level}")
return self.language_model
def generate_text(self, prompt):
"""生成文本(简化实现)"""
if self.language_model:
return self.language_model.generate(prompt)
return "模型未加载"
#E:\AI_System\agent\environment_interface.py
import os
import psutil
import platform
import json
import sqlite3
import logging
import time
from datetime import datetime
from pathlib import Path
class EnvironmentInterface:
def __init__(self, base_dir: str, coordinator=None, env_manager=None):
"""初始化环境接口
Args:
base_dir: 系统基础目录
coordinator: 意识系统协调器(可选)
env_manager: 环境管理器(包含VIP系统)
"""
self.coordinator = coordinator
self.env_manager = env_manager # 添加env_manager引用
# 配置日志 - 使用实例专属logger
self.logger = logging.getLogger(f'EnvironmentInterface_{id(self)}')
self.logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 控制台日志
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
self.logger.addHandler(console_handler)
# 工作区路径设置
self.workspace_root = self._resolve_workspace_path(base_dir)
# 创建标准目录结构
self.models_dir = self._resolve_and_create_dir("01_模型存储")
self.cache_dir = self._resolve_and_create_dir("01_模型存储/下载缓存")
self.system_dir = self._resolve_and_create_dir("02_核心代码")
self.temp_dir = self._resolve_and_create_dir("04_环境工具/临时补丁")
self.python_dir = self._resolve_and_create_dir("04_环境工具/Python环境")
# 环境配置 - 跨平台兼容
path_sep = os.pathsep
os.environ['PATH'] = f"{self.python_dir}{path_sep}{os.environ['PATH']}"
if platform.system() == "Windows":
os.environ['PATH'] += f"{path_sep}{self.python_dir}\\Scripts"
os.environ['HF_HOME'] = self.cache_dir
# 安全策略
self.authorized_actions = {
"file_access": True,
"web_search": True,
"command_exec": True,
"software_install": False,
"hardware_control": False
}
self.action_log = []
# 初始化数据库
self.environment_db = os.path.join(self.system_dir, 'environment.db')
self._init_db()
self.logger.info("✅ 环境接口初始化完成")
def _resolve_workspace_path(self, base_dir: str) -> str:
"""解析工作区路径为绝对路径"""
try:
base_path = Path(base_dir).resolve()
workspace_path = base_path / "AI_Workspace"
if not workspace_path.exists():
workspace_path.mkdir(parents=True, exist_ok=True)
self.logger.info(f"创建工作区目录: {workspace_path}")
return str(workspace_path)
except Exception as e:
self.logger.error(f"工作区路径解析失败: {str(e)}")
# 跨平台回退路径
fallback_path = Path.home() / "AI_Workspace"
fallback_path.mkdir(parents=True, exist_ok=True)
return str(fallback_path)
def _resolve_and_create_dir(self, relative_path: str) -> str:
"""解析路径并确保目录存在"""
try:
full_path = Path(self.workspace_root) / relative_path
full_path.mkdir(parents=True, exist_ok=True)
self.logger.info(f"创建/确认目录: {full_path}")
return str(full_path)
except Exception as e:
self.logger.error(f"目录解析失败: {relative_path} - {str(e)}")
# 创建临时目录作为回退
temp_path = Path(self.workspace_root) / "temp"
temp_path.mkdir(parents=True, exist_ok=True)
return str(temp_path)
def _init_db(self):
"""初始化环境数据库"""
max_retries = 3
for attempt in range(max_retries):
try:
with sqlite3.connect(self.environment_db) as conn:
cursor = conn.cursor()
# 系统信息表
cursor.execute('''CREATE TABLE IF NOT EXISTS system_info (
id INTEGER PRIMARY KEY,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
os TEXT,
cpu TEXT,
memory REAL,
disk_usage REAL
)''')
# 文件探索历史表
cursor.execute('''CREATE TABLE IF NOT EXISTS file_exploration (
id INTEGER PRIMARY KEY,
path TEXT UNIQUE,
last_visited DATETIME,
visit_count INTEGER DEFAULT 0
)''')
# 资源管理表
cursor.execute('''CREATE TABLE IF NOT EXISTS resources (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
type TEXT CHECK(type IN ('skin', 'furniture', 'tool')),
path TEXT,
is_active BOOLEAN DEFAULT 0
)''')
# 添加索引
cursor.execute("CREATE INDEX IF NOT EXISTS idx_resources_type ON resources(type)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_file_exploration_path ON file_exploration(path)")
conn.commit()
self.logger.info(f"✅ 数据库初始化完成: {self.environment_db}")
return
except (sqlite3.OperationalError, sqlite3.DatabaseError) as e:
self.logger.error(f"❌ 数据库初始化失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}")
time.sleep(1) # 等待后重试
self.logger.error("❌ 数据库初始化最终失败,环境功能可能受限")
# VIP系统功能
def request_vip_access(self, agent_id, resource_type):
"""请求VIP通道访问权限"""
if self.env_manager and hasattr(self.env_manager, 'vip_system'):
return self.env_manager.vip_system.request_access(
agent_id=agent_id,
resource=resource_type
)
self.logger.warning("VIP系统不可用")
return False
def release_vip_resource(self, agent_id, resource_type):
"""释放VIP资源"""
if self.env_manager and hasattr(self.env_manager, 'vip_system'):
self.env_manager.vip_system.release_resource(
agent_id=agent_id,
resource=resource_type
)
else:
self.logger.warning("VIP系统不可用")
def get_vip_status(self):
"""获取VIP通道状态"""
if self.env_manager and hasattr(self.env_manager, 'vip_system'):
return self.env_manager.vip_system.get_system_status()
return {"error": "VIP系统未配置"}
# 系统监控功能
def get_system_info(self) -> dict:
"""获取并记录系统信息"""
try:
mem = psutil.virtual_memory()
mem_used = round(mem.used / (1024 ** 3), 1)
mem_total = round(mem.total / (1024 ** 3), 1)
disk_usage = psutil.disk_usage('/').percent
info = {
"os": f"{platform.system()} {platform.release()}",
"cpu": f"{platform.processor()} ({psutil.cpu_count(logical=False)} cores)",
"memory": f"{mem_used}GB/{mem_total}GB ({mem.percent}%)",
"disk_usage": f"{disk_usage}%"
}
# 保存到数据库
with sqlite3.connect(self.environment_db) as conn:
cursor = conn.cursor()
cursor.execute('''INSERT INTO system_info
(os, cpu, memory, disk_usage)
VALUES (?, ?, ?, ?)''',
(info['os'], info['cpu'], mem_used, disk_usage))
conn.commit()
self.log_action("system_monitor", "采集系统信息")
return info
except Exception as e:
self.logger.error(f"❌ 获取系统信息失败: {str(e)}", exc_info=True)
return {
"error": "获取系统信息失败",
"details": str(e)
}
# 文件探索功能
def explore_directory(self, path: str = None) -> dict:
"""探索目录内容"""
try:
target_path = Path(path) if path else Path(self.workspace_root)
target_path = target_path.resolve()
# 安全路径检查
workspace_path = Path(self.workspace_root).resolve()
if not target_path.is_relative_to(workspace_path):
return {"error": "访问路径超出工作区范围"}
if not target_path.exists():
return {"error": "路径不存在"}
# 记录探索历史
self._record_exploration(str(target_path))
contents = []
for item in target_path.iterdir():
try:
item_info = {
"name": item.name,
"path": str(item),
"type": "directory" if item.is_dir() else "file",
"modified": datetime.fromtimestamp(item.stat().st_mtime).strftime("%Y-%m-%d %H:%M")
}
if item.is_file():
size = item.stat().st_size
item_info["size"] = self._format_size(size)
contents.append(item_info)
except PermissionError:
contents.append({
"name": item.name,
"error": "权限不足"
})
except Exception as e:
contents.append({
"name": item.name,
"error": str(e)
})
# 排序:目录在前,按名称排序
contents.sort(key=lambda x: (0 if x.get('type') == 'directory' else 1, x['name']))
self.log_action("file_explore", f"探索路径: {target_path}")
return {
"current_path": str(target_path),
"contents": contents
}
except Exception as e:
self.logger.error(f"❌ 探索目录失败: {str(e)}", exc_info=True)
return {"error": str(e)}
def _format_size(self, size_bytes: int) -> str:
"""格式化文件大小"""
if size_bytes < 1024:
return f"{size_bytes} B"
elif size_bytes < 1024 ** 2:
return f"{size_bytes / 1024:.1f} KB"
elif size_bytes < 1024 ** 3:
return f"{size_bytes / (1024 ** 2):.1f} MB"
else:
return f"{size_bytes / (1024 ** 3):.1f} GB"
def _record_exploration(self, path: str):
"""记录探索历史到数据库"""
try:
with sqlite3.connect(self.environment_db) as conn:
cursor = conn.cursor()
cursor.execute("SELECT 1 FROM file_exploration WHERE path = ?", (path,))
if cursor.fetchone():
cursor.execute('''UPDATE file_exploration
SET last_visited = CURRENT_TIMESTAMP,
visit_count = visit_count + 1
WHERE path = ?''', (path,))
else:
cursor.execute('''INSERT INTO file_exploration
(path, last_visited, visit_count)
VALUES (?, CURRENT_TIMESTAMP, 1)''', (path,))
conn.commit()
except Exception as e:
self.logger.error(f"❌ 记录探索历史失败: {str(e)}")
# 资源管理功能
def get_resources(self, resource_type: str = None) -> list:
"""获取资源列表(可过滤类型)"""
try:
with sqlite3.connect(self.environment_db) as conn:
cursor = conn.cursor()
if resource_type:
cursor.execute('''SELECT id, name, type, path, is_active
FROM resources
WHERE type = ?''', (resource_type,))
else:
cursor.execute('''SELECT id, name, type, path, is_active
FROM resources''')
return [{
"id": row[0],
"name": row[1],
"type": row[2],
"path": row[3],
"is_active": bool(row[4])
} for row in cursor.fetchall()]
except Exception as e:
self.logger.error(f"❌ 获取资源失败: {str(e)}")
return []
def activate_resource(self, resource_id: int) -> bool:
"""激活特定资源"""
try:
with sqlite3.connect(self.environment_db) as conn:
cursor = conn.cursor()
# 获取资源信息
cursor.execute('''SELECT type FROM resources WHERE id = ?''', (resource_id,))
resource = cursor.fetchone()
if not resource:
self.logger.warning(f"资源ID不存在: {resource_id}")
return False
resource_type = resource[0]
# 禁用同类型所有资源
cursor.execute('''UPDATE resources
SET is_active = 0
WHERE type = ?''', (resource_type,))
# 激活指定资源
cursor.execute('''UPDATE resources
SET is_active = 1
WHERE id = ?''', (resource_id,))
conn.commit()
# 记录日志
cursor.execute('''SELECT name FROM resources WHERE id = ?''', (resource_id,))
resource_name = cursor.fetchone()[0]
self.log_action("resource_activate", f"激活资源: {resource_name} ({resource_type})")
# 通知协调器
if self.coordinator:
self.coordinator.notify_resource_change(resource_type, resource_name)
return True
except Exception as e:
self.logger.error(f"❌ 激活资源失败: {str(e)}")
return False
# 工作区管理功能
def get_workspace_info(self) -> dict:
"""获取工作区信息"""
return {
"workspace_root": self.workspace_root,
"models_dir": self.models_dir,
"cache_dir": self.cache_dir,
"system_dir": self.system_dir,
"temp_dir": self.temp_dir,
"python_dir": self.python_dir
}
# 辅助功能
def is_authorized(self, action: str) -> bool:
"""检查操作授权状态"""
return self.authorized_actions.get(action, False)
def log_action(self, action: str, details: str) -> bool:
"""记录环境操作日志"""
log_entry = {
"timestamp": datetime.now().isoformat(),
"action": action,
"details": details
}
self.action_log.append(log_entry)
self.logger.info(f"{action}: {details}")
return True
def process_environment_change(self, change: dict):
"""处理环境变化(如果协调器存在)"""
if self.coordinator and hasattr(self.coordinator, 'process_stimulus'):
stimulus = self._create_stimulus_from_change(change)
self.coordinator.process_stimulus(stimulus)
def _create_stimulus_from_change(self, change: dict) -> dict:
"""将环境变化转化为刺激"""
return {
"type": "environment_change",
"source": "environment_interface",
"timestamp": datetime.now().isoformat(),
"data": change
}
# 使用示例
if __name__ == "__main__":
# 配置根日志器
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# 创建环境接口实例
current_dir = os.path.dirname(os.path.abspath(__file__))
base_dir = os.path.dirname(os.path.dirname(current_dir))
# 模拟env_manager(实际项目中应真实实现)
class MockEnvManager:
class vip_system:
@staticmethod
def request_access(agent_id, resource):
print(f"VIP访问请求: {agent_id} => {resource}")
return True
@staticmethod
def release_resource(agent_id, resource):
print(f"VIP资源释放: {agent_id} <= {resource}")
@staticmethod
def get_system_status():
return {"status": "active", "resources": 5}
env = EnvironmentInterface(
base_dir=base_dir,
env_manager=MockEnvManager() # 传入env_manager
)
# 测试VIP系统
print("\nVIP系统测试:")
print("访问权限:", env.request_vip_access("agent-001", "GPU"))
print("系统状态:", env.get_vip_status())
env.release_vip_resource("agent-001", "GPU")
# 获取工作区信息
print("\n工作区信息:")
print(json.dumps(env.get_workspace_info(), indent=2, ensure_ascii=False))
# 获取系统信息
print("\n系统信息:")
print(json.dumps(env.get_system_info(), indent=2, ensure_ascii=False))
# 探索目录
print("\n工作区内容:")
print(json.dumps(env.explore_directory(), indent=2, ensure_ascii=False))
# 测试资源管理
print("\n资源管理测试:")
print("当前资源:", env.get_resources())
# 模拟添加资源(实际应通过数据库操作)
with sqlite3.connect(env.environment_db) as conn:
cursor = conn.cursor()
cursor.execute("INSERT INTO resources (name, type, path) VALUES (?, ?, ?)",
("Theme-Dark", "skin", "/themes/dark"))
cursor.execute("INSERT INTO resources (name, type, path) VALUES (?, ?, ?)",
("Toolkit-AI", "tool", "/tools/ai_toolkit"))
conn.commit()
print("\n添加资源后:")
print(json.dumps(env.get_resources(), indent=2, ensure_ascii=False))
# 激活资源
print("\n激活资源:")
print("激活结果:", env.activate_resource(1))
print("激活后资源状态:", json.dumps(env.get_resources(), indent=2, ensure_ascii=False))
#E:\AI_System\agent\action_executor.py
import os
import subprocess
import webbrowser
import time
import sys
import logging
from typing import Dict, Any, Union
class ActionExecutor:
def __init__(self, environment_interface):
"""初始化动作执行器
Args:
environment_interface: 环境接口实例
"""
self.env = environment_interface
self.logger = logging.getLogger('ActionExecutor')
self.logger.setLevel(logging.INFO)
# 配置日志
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
self.logger.addHandler(console_handler)
self.logger.propagate = False
self.logger.info("✅ 动作执行器初始化完成")
def execute_vip_action(self, agent, action: Dict[str, Any]) -> Union[bool, Dict[str, Any]]:
"""执行VIP通道相关动作
Args:
agent: 代理对象
action: 动作字典,包含以下键:
- resource: 请求的资源类型
- name: 动作名称
- command: 要执行的命令(可选)
- params: 附加参数(可选)
Returns:
执行结果(布尔值或字典)
"""
# 1. 请求访问权限
resource = action.get('resource', 'default')
if not self.env.request_vip_access(agent.id, resource):
agent.log(f"VIP通道访问被拒绝: {resource}")
return False
# 2. 执行具体动作
try:
result = self._execute_core_action(action)
agent.log(f"VIP动作完成: {action['name']}")
return result
except Exception as e:
self.logger.error(f"VIP动作执行失败: {action['name']} - {str(e)}")
return {"error": str(e)}
finally:
# 3. 释放资源
self.env.release_vip_resource(agent.id, resource)
def _execute_core_action(self, action: Dict[str, Any]) -> Any:
"""执行核心动作逻辑
根据动作类型调用不同的执行方法
"""
action_type = action.get('type', 'command')
if action_type == 'open_file':
return self.open_file(action.get('file_path'))
elif action_type == 'open_website':
return self.open_website(action.get('url'))
elif action_type == 'install_tool':
return self.install_tool(action.get('tool_name'))
elif action_type == 'change_skin':
return self.change_skin(action.get('skin_name'))
elif action_type == 'arrange_furniture':
return self.arrange_furniture(
action.get('furniture_name'),
action.get('position')
)
elif action_type == 'run_command':
return self.run_command(action.get('command'))
else:
# 默认执行自定义命令
self.logger.info(f"执行VIP动作: {action['name']}")
time.sleep(1) # 模拟执行时间
return {"success": True, "message": f"动作 {action['name']} 执行完成"}
def open_file(self, file_path: str) -> Dict[str, Any]:
"""打开文件
Args:
file_path: 文件路径
Returns:
执行结果字典
"""
if not os.path.exists(file_path):
return {"error": "文件不存在"}
try:
# 跨平台文件打开
if os.name == 'nt': # Windows
os.startfile(file_path)
elif sys.platform == 'darwin': # macOS
subprocess.call(('open', file_path))
else: # Linux
subprocess.call(('xdg-open', file_path))
self.logger.info(f"已打开文件: {file_path}")
return {"success": True}
except Exception as e:
self.logger.error(f"打开文件失败: {str(e)}")
return {"error": str(e)}
def open_website(self, url: str) -> Dict[str, Any]:
"""打开网站
Args:
url: 网站URL
Returns:
执行结果字典
"""
try:
# 验证URL格式
if not url.startswith(('http://', 'https://')):
url = 'https://' + url
webbrowser.open(url)
self.logger.info(f"已打开网站: {url}")
return {"success": True}
except Exception as e:
self.logger.error(f"打开网站失败: {str(e)}")
return {"error": str(e)}
def install_tool(self, tool_name: str) -> Dict[str, Any]:
"""安装工具/软件
Args:
tool_name: 工具名称
Returns:
执行结果字典
"""
try:
# 实际安装逻辑 - 这里使用pip作为示例
if not self.env.is_authorized("software_install"):
return {"error": "软件安装权限不足"}
# 检查工具是否已安装
if self._is_tool_installed(tool_name):
return {"success": True, "message": f"{tool_name} 已安装"}
# 执行安装命令
result = subprocess.run(
[sys.executable, "-m", "pip", "install", tool_name],
capture_output=True,
text=True,
timeout=300 # 5分钟超时
)
if result.returncode == 0:
self.logger.info(f"成功安装工具: {tool_name}")
return {"success": True, "message": result.stdout}
else:
self.logger.error(f"安装工具失败: {tool_name}\n{result.stderr}")
return {"error": result.stderr}
except Exception as e:
self.logger.error(f"安装工具异常: {str(e)}")
return {"error": str(e)}
def _is_tool_installed(self, tool_name: str) -> bool:
"""检查工具是否已安装"""
try:
subprocess.run(
[tool_name, "--version"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
return True
except (FileNotFoundError, OSError):
return False
def change_skin(self, skin_name: str) -> Dict[str, Any]:
"""更换皮肤
Args:
skin_name: 皮肤名称
Returns:
执行结果字典
"""
try:
# 获取所有皮肤资源
skins = self.env.get_resources("skin")
# 查找匹配的皮肤
target_skin = next((s for s in skins if s["name"] == skin_name), None)
if not target_skin:
return {"error": f"找不到皮肤: {skin_name}"}
# 激活皮肤
if self.env.activate_resource(target_skin["id"]):
self.logger.info(f"已更换皮肤: {skin_name}")
return {"success": True}
else:
return {"error": f"激活皮肤失败: {skin_name}"}
except Exception as e:
self.logger.error(f"更换皮肤失败: {str(e)}")
return {"error": str(e)}
def arrange_furniture(self, furniture_name: str, position: str) -> Dict[str, Any]:
"""布置家具
Args:
furniture_name: 家具名称
position: 位置坐标 (格式: "x,y" 或 "区域名称")
Returns:
执行结果字典
"""
try:
# 在实际应用中,这里会有具体的布置逻辑
# 例如更新数据库中的位置信息或调用3D引擎
# 记录布置操作
self.env.log_action(
"arrange_furniture",
f"布置 {furniture_name} 到 {position}"
)
return {
"success": True,
"message": f"已将 {furniture_name} 放置在 {position}"
}
except Exception as e:
self.logger.error(f"布置家具失败: {str(e)}")
return {"error": str(e)}
def run_command(self, command: str) -> Dict[str, Any]:
"""运行系统命令
Args:
command: 要执行的命令
Returns:
执行结果字典
"""
if not self.env.is_authorized("command_exec"):
return {"error": "命令执行权限不足"}
try:
# 安全过滤 - 防止注入攻击
if any(bad in command for bad in [";", "&&", "||", "`", "$(", ">", "<"]):
return {"error": "检测到潜在危险命令"}
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=60 # 1分钟超时
)
output = {
"returncode": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr
}
if result.returncode == 0:
self.logger.info(f"命令执行成功: {command}")
return {"success": True, **output}
else:
self.logger.error(f"命令执行失败: {command}\n{result.stderr}")
return {"error": result.stderr, **output}
except subprocess.TimeoutExpired:
self.logger.error(f"命令执行超时: {command}")
return {"error": "命令执行超时"}
except Exception as e:
self.logger.error(f"命令执行异常: {str(e)}")
return {"error": str(e)}
# 使用示例
if __name__ == "__main__":
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# 模拟环境接口
class MockEnvInterface:
def __init__(self):
self.logger = logging.getLogger('MockEnvInterface')
self.authorized_actions = {
"command_exec": True,
"software_install": True
}
def request_vip_access(self, agent_id, resource):
self.logger.info(f"VIP访问请求: {agent_id} => {resource}")
return True
def release_vip_resource(self, agent_id, resource):
self.logger.info(f"VIP资源释放: {agent_id} <= {resource}")
def is_authorized(self, action):
return self.authorized_actions.get(action, False)
def activate_resource(self, resource_id):
self.logger.info(f"激活资源: {resource_id}")
return True
def get_resources(self, resource_type=None):
return [
{"id": 1, "name": "Theme-Dark", "type": "skin"},
{"id": 2, "name": "Theme-Light", "type": "skin"}
]
def log_action(self, action, details):
self.logger.info(f"记录动作: {action} - {details}")
return True
# 模拟代理对象
class MockAgent:
def __init__(self, agent_id):
self.id = agent_id
def log(self, message):
print(f"[Agent {self.id}] {message}")
# 创建实例
env = MockEnvInterface()
executor = ActionExecutor(env)
agent = MockAgent("agent-001")
# 测试VIP动作
print("\n测试VIP动作:")
vip_action = {
"resource": "GPU",
"name": "高性能计算",
"type": "custom",
"params": {"iterations": 1000}
}
result = executor.execute_vip_action(agent, vip_action)
print("VIP动作结果:", result)
# 测试普通动作
print("\n测试打开文件:")
print(executor.open_file("test.txt")) # 文件不存在
# print(executor.open_file("existing_file.txt")) # 实际文件
print("\n测试打开网站:")
print(executor.open_website("https://github.com"))
print("\n测试安装工具:")
print(executor.install_tool("requests")) # 实际安装
print("\n测试更换皮肤:")
print(executor.change_skin("Theme-Dark"))
print("\n测试布置家具:")
print(executor.arrange_furniture("Desk", "Room A, Position 3"))
print("\n测试运行命令:")
print(executor.run_command("echo Hello World"))
# print(executor.run_command("ls -la")) # Linux/macOS
# print(executor.run_command("dir")) # Windows
最新发布