#E:\AI_System\agent\environment_interface.py
import os
import psutil
import platform
import json
import sqlite3
import logging
import time
import sys
import traceback
from datetime import datetime
from pathlib import Path
import threading
# 添加项目根目录到路径
sys.path.append(str(Path(__file__).parent.parent))
# 导入基类
try:
from agent.base_module import EnvironmentModule
except ImportError as e:
logging.error(f"无法导入基类 EnvironmentModule: {e}")
# 创建基类的占位符
class EnvironmentModule:
def __init__(self, name):
self.name = name
self.logger = logging.getLogger(name)
def get_input(self):
return {}
def output(self, response):
print(response)
class EnvironmentInterface(EnvironmentModule):
"""环境接口模块 - 修复版"""
def __init__(self, name="EnvironmentInterface", coordinator=None, config=None):
"""初始化环境接口 - 修复日志和目录探索问题"""
# 先处理配置参数
self.coordinator = coordinator
self.config = config or {}
self.base_dir = self.config.get("base_dir", ".")
self.env_manager = self.config.get("env_manager")
# 调用父类初始化
super().__init__(name)
# 修复日志重复问题:确保只初始化一次
if not self.logger.handlers:
# 配置日志
self.logger = logging.getLogger(f'EnvironmentInterface')
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
log_level = self.config.get("log_level", "INFO")
self.logger.setLevel(getattr(logging, log_level.upper(), logging.INFO))
# 状态管理
self._status = {
"initialized": False,
"running": True,
"last_updated": time.time(),
"errors": [],
"warnings": []
}
# 安全策略
self.authorized_actions = {
"file_access": True,
"web_search": True,
"command_exec": True,
"software_install": False,
"hardware_control": False
}
self.action_log = []
self.input_queue = [] # 输入队列
self.last_interaction = time.time()
# 工作区路径设置
self.workspace_root = self._resolve_workspace_path(self.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环境")
# 环境配置 - 跨平台兼容
self._configure_path()
# 初始化数据库
self.environment_db = os.path.join(self.system_dir, 'environment.db')
self._init_db()
# 启动监控线程
self._active = True
self._monitor_thread = threading.Thread(
target=self._monitor_loop,
name="EnvMonitorThread",
daemon=True
)
self._monitor_thread.start()
self.logger.info("✅ 环境接口初始化完成")
# ===== 核心方法 =====
def _resolve_workspace_path(self, base_dir: str) -> str:
"""解析工作区根路径"""
try:
# 如果base_dir是绝对路径,直接使用
if os.path.isabs(base_dir):
workspace_root = base_dir
else:
# 否则,相对于当前文件所在目录的父目录(项目根目录)解析
project_root = Path(__file__).parent.parent
workspace_root = str(project_root / base_dir)
# 确保路径存在
os.makedirs(workspace_root, exist_ok=True)
return os.path.abspath(workspace_root)
except Exception as e:
self.logger.error(f"解析工作区路径失败: {str(e)}")
# 使用当前工作目录作为后备
return os.path.abspath(os.getcwd())
def _resolve_and_create_dir(self, relative_path: str) -> str:
"""解析并创建目录,返回绝对路径"""
full_path = os.path.join(self.workspace_root, relative_path)
os.makedirs(full_path, exist_ok=True)
return full_path
def _configure_path(self):
"""配置环境路径"""
try:
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.logger.info("环境路径配置完成")
except Exception as e:
self.logger.error(f"配置环境路径失败: {str(e)}")
self._status["errors"].append(f"PATH配置失败: {str(e)}")
def _init_db(self):
"""初始化数据库"""
try:
with sqlite3.connect(self.environment_db) as conn:
cursor = conn.cursor()
# 创建资源表
cursor.execute('''
CREATE TABLE IF NOT EXISTS resources (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
type TEXT NOT NULL,
path TEXT NOT NULL,
is_active BOOLEAN DEFAULT 0,
last_used TIMESTAMP
)
''')
# 创建VIP资源表
cursor.execute('''
CREATE TABLE IF NOT EXISTS vip_resources (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
type TEXT NOT NULL,
is_available BOOLEAN DEFAULT 1,
locked_by TEXT,
lock_time TIMESTAMP
)
''')
conn.commit()
self.logger.info(f"✅ 数据库初始化完成: {self.environment_db}")
except Exception as e:
self.logger.error(f"数据库初始化失败: {str(e)}")
self._status["errors"].append(f"数据库错误: {str(e)}")
def _monitor_loop(self):
"""监控系统状态的后台线程"""
self.logger.info("系统监控线程启动")
while self._active:
try:
# 检查系统资源使用情况
cpu_percent = psutil.cpu_percent(interval=1)
mem_usage = psutil.virtual_memory().percent
disk_usage = psutil.disk_usage(self.workspace_root).percent
# 记录到状态
self._status["cpu_usage"] = cpu_percent
self._status["memory_usage"] = mem_usage
self._status["disk_usage"] = disk_usage
self._status["last_updated"] = time.time()
# 检查空闲时间
idle_time = time.time() - self.last_interaction
if idle_time > 300: # 5分钟无交互
self.logger.warning(f"系统空闲超过5分钟,当前空闲时间: {idle_time:.1f}秒")
# 休眠直到下次检查
time.sleep(self.config.get("monitor_interval", 10))
except Exception as e:
self.logger.error(f"监控线程异常: {str(e)}")
time.sleep(10) # 出错后等待10秒再试
# ===== 实现基类接口 =====
def get_input(self):
"""获取输入 - 实现基类接口"""
if not self.input_queue:
self._generate_sample_inputs()
if self.input_queue:
return self.input_queue.pop(0)
# 默认返回空输入
return {"content": {"text": ""}, "source": "system"}
def _generate_sample_inputs(self):
"""生成示例输入 - 用于测试"""
sample_inputs = [
{"content": {"text": "Hello, how are you?"}, "source": "user"},
{"content": {"text": "What is your name?"}, "source": "user"},
{"content": {"text": "Tell me about yourself."}, "source": "user"},
{"content": {"text": "I am feeling great today."}, "source": "user"},
{"content": {"text": "My name is Alex."}, "source": "user"},
]
self.input_queue.extend(sample_inputs)
def output(self, response):
"""输出响应 - 实现基类接口"""
self.logger.info(f"💬 系统响应: {response}")
# 实际系统中应添加发送到前端或存储的逻辑
print(f">> {response}")
def add_input(self, input_data: dict):
"""添加新输入到队列"""
self.input_queue.append(input_data)
self.last_interaction = time.time()
self.logger.info(f"📥 收到新输入: {input_data}")
# ===== 环境接口功能方法 =====
def initialize(self, core):
"""初始化模块并连接到核心系统"""
if self._status["initialized"]:
self.logger.warning("系统已经初始化过")
return True
self.core_ref = core
self._status["initialized"] = True
self._status["last_updated"] = time.time()
self.logger.info("✅ 环境接口连接到核心系统")
return True
def get_workspace_info(self):
"""获取工作区信息"""
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 get_system_info(self):
"""获取系统信息"""
return {
"os": f"{platform.system()} {platform.release()}",
"cpu": f"{psutil.cpu_count(logical=False)} cores, {psutil.cpu_count()} threads",
"memory": f"{psutil.virtual_memory().total / (1024 ** 3):.2f} GB",
"disk": f"{psutil.disk_usage(self.workspace_root).total / (1024 ** 3):.2f} GB",
"python_version": platform.python_version()
}
def explore_directory(self, path=None):
"""探索目录内容 - 修复文件不存在问题"""
target_path = path or self.workspace_root
try:
# 确保目标路径存在
if not os.path.exists(target_path):
return {"error": f"路径不存在: {target_path}"}
contents = []
for entry in os.listdir(target_path):
entry_path = os.path.join(target_path, entry)
# 检查文件/目录是否存在
if not os.path.exists(entry_path):
self.logger.warning(f"文件/目录不存在: {entry_path}")
continue
is_dir = os.path.isdir(entry_path)
# 仅当是文件时才尝试获取大小
size = 0
if not is_dir and os.path.isfile(entry_path):
try:
size = os.path.getsize(entry_path)
except Exception as e:
self.logger.error(f"获取文件大小失败: {entry_path} - {str(e)}")
contents.append({
"name": entry,
"type": "directory" if is_dir else "file",
"size": size,
"modified": datetime.fromtimestamp(os.path.getmtime(entry_path)).isoformat()
})
return {
"path": target_path,
"contents": contents
}
except Exception as e:
self.logger.error(f"探索目录失败: {str(e)}")
return {"error": str(e)}
def request_vip_access(self, agent_id, resource_type):
"""请求VIP资源访问"""
# 实际实现应包括资源锁定和超时处理
self.logger.info(f"Agent {agent_id} 请求访问 {resource_type} 资源")
return True
def release_vip_resource(self, agent_id, resource_type):
"""释放VIP资源"""
self.logger.info(f"Agent {agent_id} 释放 {resource_type} 资源")
def get_vip_status(self):
"""获取VIP资源状态"""
# 实际实现应从数据库读取状态
return {
"GPU": {"available": True, "locked_by": None},
"HighMemory": {"available": True, "locked_by": None}
}
def get_resources(self):
"""获取所有资源列表"""
resources = []
try:
with sqlite3.connect(self.environment_db) as conn:
cursor = conn.cursor()
cursor.execute("SELECT id, name, type, path, is_active FROM resources")
for row in cursor.fetchall():
resources.append({
"id": row[0],
"name": row[1],
"type": row[2],
"path": row[3],
"is_active": bool(row[4])
})
except Exception as e:
self.logger.error(f"获取资源失败: {str(e)}")
return resources
def activate_resource(self, resource_id):
"""激活资源"""
try:
with sqlite3.connect(self.environment_db) as conn:
cursor = conn.cursor()
# 先停用所有同类型资源
cursor.execute(
"UPDATE resources SET is_active = 0 WHERE type IN (SELECT type FROM resources WHERE id = ?)",
(resource_id,))
# 激活指定资源
cursor.execute("UPDATE resources SET is_active = 1 WHERE id = ?", (resource_id,))
conn.commit()
return True
except Exception as e:
self.logger.error(f"激活资源失败: {str(e)}")
return False
def get_status(self):
"""获取系统状态"""
return self._status
def is_healthy(self):
"""检查系统健康状况"""
errors = self._status.get("errors", [])
if errors:
return False, f"发现 {len(errors)} 个错误"
return True, "系统运行正常"
def shutdown(self):
"""关闭系统"""
self.logger.info("🛑 关闭环境接口...")
self._active = False
self._monitor_thread.join(timeout=5)
self.logger.info("✅ 环境接口已关闭")
# 使用示例
if __name__ == "__main__":
# 配置根日志器
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# 创建环境接口配置
config = {
"base_dir": os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"log_level": "DEBUG",
"monitor_interval": 5
}
# 创建环境接口实例
env = EnvironmentInterface(config=config)
# 初始化
env.initialize(None)
print("\n===== 环境接口测试 =====")
# 测试工作区信息
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))
# 测试VIP系统
print("\nVIP系统测试:")
print("请求访问权限:", env.request_vip_access("agent-001", "GPU"))
print("VIP状态:", json.dumps(env.get_vip_status(), indent=2))
env.release_vip_resource("agent-001", "GPU")
print("释放后VIP状态:", json.dumps(env.get_vip_status(), indent=2))
# 测试资源管理
print("\n资源管理测试:")
# 添加测试资源
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("当前资源:", json.dumps(env.get_resources(), indent=2))
# 激活资源
print("\n激活资源:")
print("激活结果:", env.activate_resource(1))
print("激活后资源状态:", json.dumps(env.get_resources(), indent=2))
# 获取状态
print("\n系统状态:")
status = env.get_status()
print(json.dumps(status, indent=2, default=str))
# 健康检查
healthy, reason = env.is_healthy()
print(f"\n健康状态: {'健康' if healthy else '异常'} - {reason}")
# 关闭系统
print("\n关闭系统...")
env.shutdown()
print("✅ 测试完成")
我是让你把所有需要改的文件 改好了发给我 不是让你给我重复一遍哪里要改 我又看不懂 你发一百遍也没用 你到底在干什么?