1.# E:\AI_System\agent\environment_interface.py
import logging
import time
import queue
import threading
import json
import os
from typing import Any, Optional, Dict, List
from agent.base_module import UnifiedCognitiveModule
from core.message import Message, MessageType
from utils.shortcut_utils import ShortcutUtils
class EnvironmentInterface(UnifiedCognitiveModule):
"""环境交互接口 - 支持快捷方式解析的完整实现"""
def __init__(
self,
name: str = "EnvironmentInterface",
coordinator: Optional[Any] = None,
config: Optional[Dict] = None
):
super().__init__(name=name, coordinator=coordinator, config=config)
# 配置参数
config = config or {}
self.max_workers = config.get("max_workers", 4)
self.response_timeout = config.get("response_timeout", 30.0)
self.log_level = config.get("log_level", "INFO")
self.workspace_path = config.get("workspace_path", "E:\\AI_Workspace")
# 日志配置
self.logger = logging.getLogger("EnvironmentInterface")
log_level = getattr(logging, self.log_level.upper(), logging.INFO)
self.logger.setLevel(log_level)
# 快捷方式工具
self.shortcut_utils = ShortcutUtils()
# 工作区路径映射
self.path_mapping = self._init_path_mapping()
# 输入输出队列
self.input_queue = queue.Queue()
self.output_queue = queue.Queue()
# 线程控制
self.running = True
self.message_thread = threading.Thread(target=self._process_messages, daemon=True)
self.message_thread.start()
# 星型架构协调器引用
self.orchestrator = None
def _init_path_mapping(self) -> Dict[str, str]:
"""初始化工作区路径映射"""
mapping = {}
# 定义工作区结构
workspace_structure = {
"MODELS_DIR": "01_模型存储/主模型.lnk",
"MODEL_DOWNLOADS": "01_模型存储/下载缓存.lnk",
"AGENT_SYSTEM": "02_核心代码/Agent系统.lnk",
"BACKUP_CODE": "02_核心代码/安全备份.lnk",
"PYTHON_SCRIPTS": "03_前端交互/Python脚本.lnk",
"WEB_UI": "03_前端交互/前端代码.lnk",
"CONFIG_FILES": "03_前端交互/配置文件.lnk",
"PYTHON_ENV": "04_环境工具/Python环境.lnk",
"TEMP_PATCHES": "04_环境工具/临时补丁.lnk",
"MEMORY_CORE": "05_数据记忆/记忆核心.lnk",
"INITIAL_CODE": "06_历史备份/初始源码.lnk"
}
# 解析所有快捷方式
for key, rel_path in workspace_structure.items():
shortcut_path = os.path.join(self.workspace_path, rel_path)
target_path = self.shortcut_utils.resolve_shortcut(shortcut_path)
if target_path and os.path.exists(target_path):
mapping[key] = target_path
self.logger.info(f"映射工作区路径: {key} -> {target_path}")
else:
self.logger.warning(f"无法解析工作区路径: {key} ({shortcut_path})")
return mapping
def resolve_workspace_path(self, path_key: str) -> Optional[str]:
"""
解析工作区路径
:param path_key: 路径键名 (如 "MODELS_DIR")
:return: 实际路径或None
"""
return self.path_mapping.get(path_key)
# ============ 关键修复:实现必需的抽象方法 ============
def process_command(self, command: str) -> dict:
"""处理命令 - 实现抽象方法"""
self.logger.info(f"处理环境命令: {command}")
# 特殊命令处理
if command == "workspace_status":
return {
"status": "success",
"workspace": self.workspace_path,
"mappings": self.path_mapping
}
elif command.startswith("resolve_path "):
path_key = command[13:] # 移除 "resolve_path " 前缀
resolved_path = self.resolve_workspace_path(path_key)
return {
"status": "success" if resolved_path else "error",
"key": path_key,
"path": resolved_path
}
return {
"status": "成功",
"message": f"环境接口 '{self.name}' 已处理命令: {command}",
"command": command
}
def connect(self) -> bool:
"""连接环境 - 实现抽象方法"""
self.logger.info("连接到环境接口...")
return True
def disconnect(self):
"""断开连接 - 实现抽象方法"""
self.logger.info("断开环境接口连接...")
# 断开连接逻辑
# ============ 原有功能保持不变 ============
def set_orchestrator(self, orchestrator):
"""连接中枢协调器"""
self.orchestrator = orchestrator
def is_healthy(self) -> bool:
"""健康检查"""
return self.running and self.message_thread.is_alive()
def get_status(self) -> dict:
"""返回模块状态"""
return {
"status": "running" if self.running else "stopped",
"module": self.name,
"input_queue": self.input_queue.qsize(),
"output_queue": self.output_queue.qsize(),
"thread_alive": self.message_thread.is_alive(),
"workspace_mappings": len(self.path_mapping)
}
def shutdown(self) -> bool:
"""关闭环境接口"""
try:
self.running = False
if self.message_thread.is_alive():
self.message_thread.join(timeout=2.0)
self.logger.info("🛑 环境接口已关闭")
return True
except Exception as e:
self.logger.error(f"❌ 关闭失败: {str(e)}")
return False
# ... 其余方法保持不变 ...
def process(self, input_data: Any) -> dict:
"""处理输入数据"""
if isinstance(input_data, dict):
self.add_input(input_data)
return {"status": "queued"}
elif isinstance(input_data, str):
self.add_input({"command": input_data})
return {"status": "queued"}
else:
return {"error": "不支持的输入类型"}
def _process_messages(self):
"""处理消息的后台线程"""
while self.running:
try:
# 获取用户输入
user_input = self.get_input(timeout=0.5)
if user_input:
# 发送到协调器(星型架构)
message = Message(
msg_type=MessageType.EVENT,
sender=self.name,
content=user_input,
target="CognitiveOrchestrator" # 直接发给协调器
)
# 通过协调器处理,如果没有协调器则尝试直接发送
if self.orchestrator:
self.orchestrator.handle_message(message)
else:
self.logger.warning("⚠️ 协调器未连接,无法发送消息")
self.logger.debug(f"📤 发送用户输入: {user_input['command'][:20]}...")
# 处理输出队列
if not self.output_queue.empty():
output = self.output_queue.get_nowait()
self._display_output(output)
except Exception as e:
self.logger.error(f"消息处理出错: {str(e)}")
time.sleep(0.1)
def handle_message(self, message: Message):
"""处理接收到的消息"""
if message.target and message.target != self.name:
return
self.logger.debug(f"📩 收到消息 [{message.sender}]: {message.msg_type.name}")
# 根据消息类型处理
if message.msg_type in [MessageType.DATA, MessageType.RESPONSE]:
self.output(message.content)
elif message.msg_type == MessageType.STATUS:
self.logger.info(f"系统状态更新: {message.content}")
def get_input(self, timeout: float = 0.5) -> Optional[Dict]:
"""获取输入"""
try:
return self.input_queue.get(timeout=timeout)
except queue.Empty:
return None
def output(self, response: Any):
"""添加响应"""
self.output_queue.put(response)
def _display_output(self, response: Any):
"""格式化并显示输出"""
try:
# 处理不同类型的响应
if isinstance(response, dict):
response.setdefault("timestamp", time.time())
response.setdefault("source", "system")
response_str = json.dumps(response, ensure_ascii=False, indent=2)
print(f"<< {response_str}")
if "message" in response:
self.logger.info(f"💬 系统响应: {response['message']}")
else:
self.logger.info("💬 系统响应: 无内容")
elif isinstance(response, str):
print(f"<< {response}")
self.logger.info(f"💬 系统响应: {response}")
elif isinstance(response, Message):
print(f"<< [Message from {response.sender}]: {response.content[:50]}...")
self.logger.info(f"💬 收到消息响应: {response.content[:50]}...")
else:
response_str = str(response)
print(f"<< {response_str}")
self.logger.info(f"💬 系统响应: {response_str}")
except Exception as e:
self.logger.error(f"输出响应失败: {str(e)}")
def add_input(self, input_data: dict):
"""添加新输入"""
if not isinstance(input_data, dict):
self.logger.error("输入数据格式错误,必须是字典")
return
input_data.setdefault("timestamp", time.time())
input_data.setdefault("source", "user")
self.input_queue.put(input_data)
self.logger.debug(f"手动添加输入: {input_data['command'][:20]}...")
def get_health_status(self) -> dict:
"""返回模块健康状态"""
return {
"status": "running" if self.running else "stopped",
"module": self.name,
"queue_size": self.input_queue.qsize(),
"last_activity": time.time(),
"output_queue_size": self.output_queue.qsize()
}
2.# environment_interface.py
class EnvironmentInterface:
# ... 现有代码 ...
def get_system_resources(self):
"""获取系统资源状态"""
try:
import psutil
return {
"cpu_percent": psutil.cpu_percent(),
"memory_used": psutil.virtual_memory().percent,
"gpu_memory": self._get_gpu_usage()
}
except ImportError:
return {"error": "psutil未安装"}
def _get_gpu_usage(self):
"""获取GPU使用情况"""
if torch.cuda.is_available():
return {
device: torch.cuda.memory_allocated(device)
for device in range(torch.cuda.device_count())
}
return {}
最新发布