EXCEPTION_RECORD structure

本文详细解析了Windows异常处理中EXCEPTION_RECORD结构体的各成员含义,包括异常代码、异常标志、异常记录、异常地址、参数数量以及异常信息数组等关键信息。文章深入探讨了不同异常代码的含义及其应用场景,对于理解和处理Windows系统异常提供了宝贵的指导。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接:http://msdn.microsoft.com/en-us/library/windows/desktop/ms679308%28v=vs.85%29.aspx

本文链接:http://blog.youkuaiyun.com/wlsgzl/article/details/18763625

Describes an exception.描述异常的结构体

Syntax

C++
typedef struct _EXCEPTION_RECORD {
  DWORD                    ExceptionCode;
  DWORD                    ExceptionFlags;
  struct _EXCEPTION_RECORD  *ExceptionRecord;
  PVOID                    ExceptionAddress;
  DWORD                    NumberParameters;
  ULONG_PTR                ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
} EXCEPTION_RECORD, *PEXCEPTION_RECORD;

Members

ExceptionCode

The reason the exception occurred. 产生异常的原因。This is the code generated by a hardware exception, or the code specified in theRaiseException function for a software-generated exception. 这是一个硬件异常产生的代码或者由RaiseException函数指定产生的软件异常码。The following tables describes the exception codes that are likely to occur due to common programming errors.

ValueMeaning
EXCEPTION_ACCESS_VIOLATION

The thread tried to read from or write to a virtual address for which it does not have the appropriate access.线程违规读写没有适当权限的虚拟地址。

EXCEPTION_ARRAY_BOUNDS_EXCEEDED

The thread tried to access an array element that is out of bounds and the underlying hardware supports bounds checking.线程在底层硬件支持的边界检查下访问数组越界。

EXCEPTION_BREAKPOINT

A breakpoint was encountered.遇到一个断点。

EXCEPTION_DATATYPE_MISALIGNMENT

The thread tried to read or write data that is misaligned on hardware that does not provide alignment.线程试图在不支持对齐的硬件上读写未对齐的数据。 For example, 16-bit values must be aligned on 2-byte boundaries; 32-bit values on 4-byte boundaries, and so on.例如,16位值必须2字节对齐,32位值必须4字节对齐,以此类推。

EXCEPTION_FLT_DENORMAL_OPERAND

One of the operands in a floating-point operation is denormal.浮点操作的一个操作数不正规。 A denormal value is one that is too small to represent as a standard floating-point value.不正规的值表示太小而不能表示一个标准的浮点值。

EXCEPTION_FLT_DIVIDE_BY_ZERO

The thread tried to divide a floating-point value by a floating-point divisor of zero.线程浮点除零操作。

EXCEPTION_FLT_INEXACT_RESULT

The result of a floating-point operation cannot be represented exactly as a decimal fraction.浮点结果的操作不能准确的代替小数。

EXCEPTION_FLT_INVALID_OPERATION

This exception represents any floating-point exception not included in this list.这个异常代表了这个列表里没有列出的其他浮点异常。

EXCEPTION_FLT_OVERFLOW

The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.浮点操作的指数超过了相应类型的最大值。

EXCEPTION_FLT_STACK_CHECK

The stack overflowed or underflowed as the result of a floating-point operation.浮点操作的栈越界或下溢出。

EXCEPTION_FLT_UNDERFLOW

The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.浮点操作的指数没有超过相应类型的最大值。

EXCEPTION_ILLEGAL_INSTRUCTION

The thread tried to execute an invalid instruction.线程试图执行无效指令。

EXCEPTION_IN_PAGE_ERROR

The thread tried to access a page that was not present, and the system was unable to load the page.线程试图访问一个不存在的页或者无法加载的页。 For example, this exception might occur if a network connection is lost while running a program over the network.例如,异常可能在运行的网络程序丢失连接的时候发生。

EXCEPTION_INT_DIVIDE_BY_ZERO

The thread tried to divide an integer value by an integer divisor of zero.线程试图整数除零。

EXCEPTION_INT_OVERFLOW

The result of an integer operation caused a carry out of the most significant bit of the result.整数操作的结果占用了结果的最大符号位。

EXCEPTION_INVALID_DISPOSITION

An exception handler returned an invalid disposition to the exception dispatcher.异常处理程序给异常调度器返回了一个无效配置。 Programmers using a high-level language such as C should never encounter this exception.使用高级语言(例如C语言)的程序永远不会遇到这个异常。

EXCEPTION_NONCONTINUABLE_EXCEPTION

The thread tried to continue execution after a noncontinuable exception occurred.线程试图在一个不可继续执行的异常发生后继续执行。

EXCEPTION_PRIV_INSTRUCTION

The thread tried to execute an instruction whose operation is not allowed in the current machine mode.线程试图执行当前机器模式不支持的指令。

EXCEPTION_SINGLE_STEP

A trace trap or other single-instruction mechanism signaled that one instruction has been executed.(简单的说是)单步。

EXCEPTION_STACK_OVERFLOW

The thread used up its stack.(简单的说是)栈溢出。

 

Another exception code is likely to occur when debugging console processes.其他的异常在调试控制台程序的时候可能发生。 It does not arise because of a programming error. 因为编程的错误可能不会发生。TheDBG_CONTROL_C exception code occurs when CTRL+C is input to a console process that handles CTRL+C signals and is being debugged. DBG_CONTROL_C异常码在调试控制台程序时输入CTRL+C来处理CTRL+C信号的时候发生。This exception code is not meant to be handled by applications. 这个异常码并不会被应用程序处理。It is raised only for the benefit of the debugger, and is raised only when a debugger is attached to the console process.它的产生只是更好的为调试器服务,也只在调试器附加到控制台程序的时候发生。

ExceptionFlags

The exception flags.异常标志。 This member can be either zero, indicating a continuable exception, or EXCEPTION_NONCONTINUABLE indicating a noncontinuable exception.这个参数可以是0,表示可继续执行的异常,也可以是EXCEPTION_NONCONTINUABLE表示不可继续执行的异常。 Any attempt to continue execution after a noncontinuable exception causes theEXCEPTION_NONCONTINUABLE_EXCEPTION exception.任何试图在不可继续执行的异常发生后继续执行会产生EXCEPTION_NONCONTINUABLE_EXCEPTION异常。

ExceptionRecord

A pointer to an associated EXCEPTION_RECORD structure. 指向EXCEPTION_RECORD结构体的指针。Exception records can be chained together to provide additional information when nested exceptions occur.当嵌套异常发生的时候,异常记录可以形成一个链来提供额外的信息。

ExceptionAddress

The address where the exception occurred.异常发生的地址。

NumberParameters

The number of parameters associated with the exception. 与异常相关的参数个数。This is the number of defined elements in theExceptionInformation array.这是theExceptionInformation数组的元素个数。

ExceptionInformation

An array of additional arguments that describe the exception. 用于描述异常的附加参数的数组。TheRaiseException function can specify this array of arguments. RaiseException函数可以指定这个参数数组。For most exception codes, the array elements are undefined. 对大多数异常码而言,这个数组元素是未定义的。The following table describes the exception codes whose array elements are defined.下面的表格展示了哪些异常码的数组元素是定义了的。

Exception codeMeaning
EXCEPTION_ACCESS_VIOLATION

The first element of the array contains a read-write flag that indicates the type of operation that caused the access violation. 数组的第一个元素包含了一个读写标志,表示引起访问违规的操作类型。If this value is zero, the thread attempted to read the inaccessible data. 如果这个值为0,表示线程试图读取不可访问的数据。If this value is 1, the thread attempted to write to an inaccessible address. 如果这个值为1,表示线程试图写入不可访问的地址。If this value is 8, the thread causes a user-mode data execution prevention (DEP) violation.如果这个值是8,表示线程线程引发了一个用户模式的DEP违规。

The second array element specifies the virtual address of the inaccessible data.数组的第二个元素指定了不可访问数据的虚拟地址。

EXCEPTION_IN_PAGE_ERROR

The first element of the array contains a read-write flag that indicates the type of operation that caused the access violation. 数组的第一个元素包含了一个读写标志,用于表示引起访问违规的操作类型。If this value is zero, the thread attempted to read the inaccessible data. 如果值为0,表示线程试图读取不可访问的数据。If this value is 1, the thread attempted to write to an inaccessible address. 如果值为1,表示线程试图写入不可访问的地址。If this value is 8, the thread causes a user-mode data execution prevention (DEP) violation.如果值为8,表示线程引起了一个用户模式的DEP违规。

The second array element specifies the virtual address of the inaccessible data.数组的第二个元素指定了不可访问数据的虚拟地址。

The third array element specifies the underlying NTSTATUS code that resulted in the exception.数组的第三个元素表示底层的NTSTATUS码引起的本次异常。

 

Remarks

To enable a debugger to debug a target that is running on a different architecture (32-bit versus 64-bit), use one of the explicit forms of this structure.

1: kd> !analyze -v ******************************************************************************* * * * Bugcheck Analysis * * * ******************************************************************************* WHEA_UNCORRECTABLE_ERROR (124) A fatal hardware error has occurred. Parameter 1 identifies the type of error source that reported the error. Parameter 2 holds the address of the nt!_WHEA_ERROR_RECORD structure that describes the error condition. Try !errrec Address of the nt!_WHEA_ERROR_RECORD structure to get more details. Arguments: Arg1: 00000000, Machine Check Exception Arg2: 8712401c, Address of the nt!_WHEA_ERROR_RECORD structure. Arg3: f61f3440, High order 32-bits of the MCi_STATUS value. Arg4: 00040150, Low order 32-bits of the MCi_STATUS value. Debugging Details: ------------------ KEY_VALUES_STRING: 1 Key : Analysis.CPU.mSec Value: 3265 Key : Analysis.Elapsed.mSec Value: 7600 Key : Analysis.IO.Other.Mb Value: 0 Key : Analysis.IO.Read.Mb Value: 1 Key : Analysis.IO.Write.Mb Value: 0 Key : Analysis.Init.CPU.mSec Value: 750 Key : Analysis.Init.Elapsed.mSec Value: 18752 Key : Analysis.Memory.CommitPeak.Mb Value: 79 Key : Analysis.Version.DbgEng Value: 10.0.27793.1000 Key : Analysis.Version.Description Value: 10.2410.02.02 amd64fre Key : Analysis.Version.Ext Value: 1.2410.2.2 Key : Bugcheck.Code.LegacyAPI Value: 0x124 Key : Bugcheck.Code.TargetModel Value: 0x124 Key : Failure.Bucket Value: 0x124_0_GenuineIntel_PROCESSOR_CACHE_IMAGE_GenuineIntel.sys Key : Failure.Hash Value: {b70a049a-4a17-5749-b5df-df070316ca7d} Key : Hypervisor.Flags.Value Value: 0 Key : Hypervisor.Flags.ValueHex
04-02
我已经建好了数据库只需链接即可-- 创建数据库并设置字符集 CREATE DATABASE IF NOT EXISTS `warehouse_management_system` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; USE `warehouse_management_system`; SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for goods -- ---------------------------- DROP TABLE IF EXISTS `goods`; CREATE TABLE `goods` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '主键', `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '货名', `storage` int NOT NULL COMMENT '仓库', `goodsType` int NOT NULL COMMENT '分类', `count` int NULL DEFAULT NULL COMMENT '数量', `remark` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`) USING BTREE, -- 添加外键约束 CONSTRAINT `fk_goods_storage` FOREIGN KEY (`storage`) REFERENCES `storage` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_goods_type` FOREIGN KEY (`goodsType`) REFERENCES `goodstype` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for goodstype -- ---------------------------- DROP TABLE IF EXISTS `goodstype`; CREATE TABLE `goodstype` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '主键', `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '分类名', `remark` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for menu -- ---------------------------- DROP TABLE IF EXISTS `menu`; CREATE TABLE `menu` ( `id` int NOT NULL, `menuCode` varchar(8) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '菜单编码', `menuName` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '菜单名字', `menuLevel` varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '菜单级别', `menuParentCode` varchar(8) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '菜单的父code', `menuClick` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '点击触发的函数', `menuRight` varchar(8) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '权限 0超级管理员,1表示管理员,2表示普通用户,可以用逗号组合使用', `menuComponent` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, `menuIcon` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for record -- ---------------------------- DROP TABLE IF EXISTS `record`; CREATE TABLE `record` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '主键', `goods` int NOT NULL COMMENT '货品id', `userId` int NULL DEFAULT NULL COMMENT '取货人/补货人', `admin_id` int NULL DEFAULT NULL COMMENT '操作人id', `count` int NULL DEFAULT NULL COMMENT '数量', `createtime` datetime NULL DEFAULT NULL COMMENT '操作时间', `remark` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`) USING BTREE, -- 添加外键约束 CONSTRAINT `fk_record_goods` FOREIGN KEY (`goods`) REFERENCES `goods` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_record_user` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `fk_record_admin` FOREIGN KEY (`admin_id`) REFERENCES `user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for storage -- ---------------------------- DROP TABLE IF EXISTS `storage`; CREATE TABLE `storage` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '主键', `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '仓库名', `remark` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '主键', `no` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '账号', `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '名字', `password` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '密码', `age` int NULL DEFAULT NULL, `sex` int NULL DEFAULT NULL COMMENT '性别', `phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '电话', `role_id` int NULL DEFAULT NULL COMMENT '角色 0超级管理员,1管理员,2普通账号', `isValid` varchar(4) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'Y' COMMENT '是否有效,Y有效,其他无效', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of goodstype -- ---------------------------- INSERT INTO `goodstype` VALUES (1, '电子产品', '手机、电脑、平板、单反'); INSERT INTO `goodstype` VALUES (2, '医疗用品', '感冒药、退烧药、止疼药'); INSERT INTO `goodstype` VALUES (3, '生活用品', '牙刷、毛巾、洗面奶'); -- ---------------------------- -- Records of storage -- ---------------------------- INSERT INTO `storage` VALUES (1, '上海仓库', '上海各区仓库管理'); INSERT INTO `storage` VALUES (2, '杭州仓库', '杭州各区仓库管理'); INSERT INTO `storage` VALUES (3, '苏州仓库', '苏州各区仓库管理'); -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES (1, 'admin', '超级管理员', 'root', 18, 1, '13215227869', 0, 'Y'); INSERT INTO `user` VALUES (2, 'sa', '管理员', 'root', 19, 0, '13215223466', 1, 'Y'); INSERT INTO `user` VALUES (3, 'gaze', '用户1', '123456', 29, 1, '13215228462', 2, 'Y'); INSERT INTO `user` VALUES (4, 'marin', '用户2', '123456', 18, 1, '18866669998', 2, 'Y'); INSERT INTO `user` VALUES (5, 'susic', '用户3', '123456', 22, 0, '13700000044', 2, 'Y'); INSERT INTO `user` VALUES (6, 'suke', '用户4', '123456', 32, 1, '18866669998', 1, 'Y'); -- ---------------------------- -- Records of menu -- ---------------------------- INSERT INTO `menu` VALUES (1, '001', '管理员管理', '1', NULL, 'Admin', '0', 'admin/AdminManage.vue', 'el-icon-s-custom'); INSERT INTO `menu` VALUES (2, '002', '用户管理', '1', NULL, 'User', '0,1', 'user/UserManage.vue', 'el-icon-user-solid'); INSERT INTO `menu` VALUES (3, '003', '仓库管理', '1', NULL, 'Storage', '0,1', 'storage/StorageManage', 'el-icon-office-building'); INSERT INTO `menu` VALUES (4, '004', '物品分类管理', '1', NULL, 'Goodstype', '0,1', 'goodstype/GoodstypeManage', 'el-icon-menu'); INSERT INTO `menu` VALUES (5, '005', '物品管理 ', '1', NULL, 'Goods', '0,1,2', 'goods/GoodsManage', 'el-icon-s-management'); INSERT INTO `menu` VALUES (6, '006', '记录管理', '1', NULL, 'Record', '0,1,2', 'record/RecordManage', 'el-icon-s-order'); -- ---------------------------- -- Records of goods -- ---------------------------- INSERT INTO `goods` VALUES (1, '牙刷', 2, 3, 198, '名牌'); INSERT INTO `goods` VALUES (2, '华为手机', 1, 1, 1008, '只限今年售卖'); INSERT INTO `goods` VALUES (3, '止疼药', 3, 2, 10933, '处方开药'); -- ---------------------------- -- Records of record -- ---------------------------- INSERT INTO `record` VALUES (1, 2, 4, 1, 9, '2023-02-16 15:26:02', '半价'); INSERT INTO `record` VALUES (2, 1, 3, 1, 99, '2023-02-16 15:26:29', '名牌'); INSERT INTO `record` VALUES (3, 3, 5, 1, 999, '2023-02-16 15:27:04', '医生处方'); INSERT INTO `record` VALUES (4, 3, 4, 1, -65, '2023-02-16 15:28:06', '急需'); SET FOREIGN_KEY_CHECKS = 1;
06-21
import os import time import logging # 使用绝对导入 from core.config import system_config from core.environment import DefaultEnvironment, AIHome, ActionExecutor # 修改导入为具体实现类 class AutonomousAgent: def __init__(self): self.logger = self._setup_logger() self.logger.info("🔁 初始化自主智能体核心模块...") try: # 初始化环境感知系统 - 修复部分 self._initialize_environment_systems() # 初始化各子系统 self._initialize_subsystems() self.logger.info("✅ 自主智能体初始化完成") except Exception as e: self.logger.error(f"❌ 智能体初始化失败: {str(e)}") raise def _setup_logger(self): """配置日志记录器""" logger = logging.getLogger('AutonomousAgent') logger.setLevel(system_config.LOG_LEVEL) # 创建控制台处理器 console_handler = logging.StreamHandler() console_handler.setLevel(system_config.LOG_LEVEL) # 创建格式化器 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) # 添加处理器 logger.addHandler(console_handler) logger.propagate = False return logger def _initialize_environment_systems(self): """初始化环境感知系统 - 修复后""" # 获取项目根目录 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 修复:使用具体实现类 DefaultEnvironment self.environment = DefaultEnvironment(base_dir) # 传递 base_dir self.logger.info("✅ 环境接口初始化完成") # 初始化智能家居环境 self.home = AIHome(base_dir) self.logger.info("✅ 智能家居环境初始化完成") # 修复:ActionExecutor 不需要参数 self.executor = ActionExecutor() # 移除环境参数 self.logger.info("✅ 动作执行器初始化完成") # 记录环境状态 env_status = self.environment.get_system_info() self.logger.info(f"📊 系统状态: OS={env_status['os']}, CPU={env_status['cpu']}, " f"内存={env_status['memory']}GB, 磁盘={env_status['disk_usage']}%") def _initialize_subsystems(self): """初始化所有子系统""" # 1. 初始化模型管理器 from .model_manager import ModelManager self.model_manager = ModelManager( model_dir=system_config.MODEL_DIR, device=system_config.DEVICE, default_model=system_config.DEFAULT_MODEL ) self.logger.info("✅ 模型管理器初始化完成") # 2. 初始化健康系统 from .health_system import HealthSystem self.health_system = HealthSystem(self) self.logger.info("✅ 健康系统初始化完成") # 3. 初始化记忆系统 from .memory_system import MemorySystem self.memory_system = MemorySystem(self) self.logger.info("✅ 记忆系统初始化完成") # 4. 初始化情感系统 from .affective_system import AffectiveSystem self.affective_system = AffectiveSystem(agent=self) self.logger.info("✅ 情感系统初始化完成") # 5. 初始化认知架构 from .cognitive_architecture import CognitiveArchitecture self.cognitive_architecture = CognitiveArchitecture(agent=self) self.logger.info("✅ 认知架构初始化完成") # 6. 初始化通信系统 from .communication_system import CommunicationSystem self.communication_system = CommunicationSystem( cognitive_system=self.cognitive_architecture, agent=self # 传递智能体实例 ) self.logger.info("✅ 通信系统初始化完成") def process_input(self, user_input, user_id="default"): """处理用户输入(通过通信系统)""" return self.communication_system.process_input(user_input, user_id) def run_periodic_tasks(self): """运行周期性任务""" # 更新健康状态 self.health_system.update() # 情感系统更新 self.affective_system.grow() # 记忆系统维护 self.memory_system.consolidate_memories() # 修复:环境状态监控 - 使用时间戳 current_time = time.time() if not hasattr(self, "_last_env_check"): self._last_env_check = current_time # 每5分钟检查一次 if current_time - self._last_env_check > 300: self._last_env_check = current_time self._monitor_environment() def _monitor_environment(self): """监控环境状态 - 修复后""" try: # 获取当前系统状态 env_status = self.environment.get_system_info() # 安全解析磁盘使用率 disk_str = env_status.get('disk_usage', '0%').strip() if disk_str.endswith('%'): try: disk_usage = float(disk_str[:-1]) except ValueError: disk_usage = 0.0 else: disk_usage = 0.0 if disk_usage > 90: self.logger.warning(f"⚠️ 磁盘空间不足!当前使用率: {disk_usage}%") # 安全解析内存使用 memory_str = env_status.get('memory', '0GB/0GB') try: # 支持多种格式: "3.2GB/16GB" "3.2/16.0 GB" parts = memory_str.replace('GB', '').replace(' ', '').split('/') if len(parts) >= 2: memory_used = float(parts[0]) memory_total = float(parts[1]) memory_ratio = memory_used / memory_total if memory_ratio > 0.85: self.logger.warning( f"⚠️ 内存使用过高!已用: {memory_used:.1f}GB, " f"总共: {memory_total:.1f}GB, " f"使用率: {memory_ratio * 100:.1f}%" ) except (ValueError, TypeError, ZeroDivisionError) as e: self.logger.error(f"内存数据解析失败: {memory_str} - {str(e)}") # 记录到健康系统 self.health_system.record_environment_status(env_status) except Exception as e: self.logger.error(f"环境监控失败: {str(e)}", exc_info=True) def get_status(self): """获取智能体状态报告""" # 获取基础状态 status = { "health": self.health_system.get_status(), "affective": self.affective_system.get_state(), "memory_stats": self.memory_system.get_stats(), "model": self.model_manager.get_current_model_info() } # 添加环境信息 try: env_status = self.environment.get_system_info() status["environment"] = { "os": env_status.get("os", "知"), "cpu": env_status.get("cpu", "0%"), "memory": env_status.get("memory", "0GB/0GB"), "disk": env_status.get("disk_usage", "0%") } except Exception as e: status["environment"] = {"error": str(e)} return status # 环境交互方法 def explore_environment(self, path=None): """探索环境目录""" try: return self.environment.explore_directory(path) except Exception as e: self.logger.error(f"环境探索失败: {str(e)}") return {"error": str(e)} def execute_action(self, action, parameters): """通过执行器执行动作""" try: result = self.executor.execute(action, parameters) self.logger.info(f"执行动作: {action} {parameters} → {result.get('status', '知')}") return result except Exception as e: self.logger.error(f"动作执行失败: {action} {parameters} - {str(e)}") return {"status": "error", "message": str(e)} import os import psutil import platform import json import sqlite3 import sys import subprocess import requests import logging from datetime import datetime # 修复快捷方式解析问题 def resolve_shortcut(path): """解析快捷方式路径(简化实现)""" if sys.platform == 'win32': if path.endswith('.lnk'): # Windows 系统下解析 .lnk 文件 try: import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(path) return shortcut.Targetpath except ImportError: # 如果没有 win32com 模块,直接返回路径 return path # 非 Windows 系统非快捷文件直接返回 return path class EnvironmentInterface: def __init__(self): # 配置日志 self.logger = logging.getLogger('EnvironmentInterface') self.logger.setLevel(logging.INFO) console_handler = logging.StreamHandler() console_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) self.logger.addHandler(console_handler) # 工作区路径设置 self.workspace_root = "E:\\AI_Workspace" # 解析路径并确保目录存在 self.models_dir = self._resolve_and_create_dir(os.path.join(self.workspace_root, "01_模型存储", "主模型.lnk")) self.cache_dir = self._resolve_and_create_dir(os.path.join(self.workspace_root, "01_模型存储", "下载缓存.lnk")) self.system_dir = self._resolve_and_create_dir( os.path.join(self.workspace_root, "02_核心代码", "Agent系统.lnk")) self.temp_dir = self._resolve_and_create_dir(os.path.join(self.workspace_root, "04_环境工具", "临时补丁.lnk")) self.python_dir = self._resolve_and_create_dir( os.path.join(self.workspace_root, "04_环境工具", "Python环境.lnk")) # 环境配置 os.environ['PATH'] = f"{self.python_dir};{self.python_dir}\\Scripts;{os.environ['PATH']}" 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_and_create_dir(self, path): """解析路径并确保目录存在""" resolved = resolve_shortcut(path) # 如果是文件路径,获取其目录 if os.path.isfile(resolved): dir_path = os.path.dirname(resolved) else: dir_path = resolved # 创建目录(如果不存在) if not os.path.exists(dir_path): os.makedirs(dir_path, exist_ok=True) self.logger.info(f"创建目录: {dir_path}") return resolved def _init_db(self): """初始化环境数据库""" conn = sqlite3.connect(self.environment_db) c = conn.cursor() # 系统信息表 c.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 )''') # 文件探索历史表 c.execute('''CREATE TABLE IF NOT EXISTS file_exploration ( id INTEGER PRIMARY KEY, path TEXT UNIQUE, last_visited DATETIME, visit_count INTEGER DEFAULT 0 )''') # 资源管理表 c.execute('''CREATE TABLE IF NOT EXISTS resources ( id INTEGER PRIMARY KEY, name TEXT, type TEXT, -- skin, furniture, tool path TEXT, is_active BOOLEAN DEFAULT 0 )''') conn.commit() conn.close() self.logger.info(f"数据库初始化完成: {self.environment_db}") # 系统监控功能 def get_system_info(self): """获取并记录系统信息""" 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", "disk_usage": f"{disk_usage}%" } # 保存到数据库 conn = sqlite3.connect(self.environment_db) c = conn.cursor() c.execute('''INSERT INTO system_info (os, cpu, memory, disk_usage) VALUES (?, ?, ?, ?)''', (info['os'], info['cpu'], mem_used, disk_usage)) conn.commit() conn.close() self.log_action("system_monitor", "采集系统信息") return info except Exception as e: self.logger.error(f"获取系统信息失败: {str(e)}") return { "os": f"Error: {str(e)}", "cpu": "0%", "memory": "0GB/0GB", "disk_usage": "0%" } # 文件探索功能 def explore_directory(self, path=None): """探索目录内容""" try: target_path = path or self.workspace_root target_path = os.path.abspath(target_path) # 安全路径检查 if not target_path.startswith(os.path.abspath(self.workspace_root)): return {"error": "访问路径超出工作区范围"} if not os.path.exists(target_path): return {"error": "路径不存在"} # 记录探索历史 self._record_exploration(target_path) contents = [] for item in os.listdir(target_path): full_path = os.path.join(target_path, item) try: is_dir = os.path.isdir(full_path) size = os.path.getsize(full_path) if not is_dir else 0 modified_time = os.path.getmtime(full_path) contents.append({ "name": item, "type": "directory" if is_dir else "file", "path": full_path, "size": f"{size / 1024:.1f}KB" if size < 1024 ** 2 else f"{size / (1024 ** 2):.1f}MB", "modified": datetime.fromtimestamp(modified_time).strftime("%Y-%m-%d %H:%M") }) except PermissionError: contents.append({ "name": item, "type": "unknown", "error": "权限不足" }) except Exception as e: contents.append({ "name": item, "type": "unknown", "error": str(e) }) self.log_action("file_explore", f"探索路径: {target_path}") return { "current_path": target_path, "contents": sorted(contents, key=lambda x: (x['type'] == 'directory', x['name']), reverse=True) } except Exception as e: self.logger.error(f"探索目录失败: {str(e)}") return {"error": str(e)} def _record_exploration(self, path): """记录探索历史到数据库""" try: conn = sqlite3.connect(self.environment_db) c = conn.cursor() c.execute("SELECT id FROM file_exploration WHERE path = ?", (path,)) if c.fetchone(): c.execute('''UPDATE file_exploration SET last_visited = CURRENT_TIMESTAMP, visit_count = visit_count + 1 WHERE path = ?''', (path,)) else: c.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)}") finally: conn.close() def get_exploration_history(self): """获取探索历史记录""" try: conn = sqlite3.connect(self.environment_db) c = conn.cursor() c.execute('''SELECT path, last_visited, visit_count FROM file_exploration ORDER BY last_visited DESC LIMIT 10''') history = [ {"path": item[0], "last_visited": item[1], "visit_count": item[2]} for item in c.fetchall() ] return history except Exception as e: self.logger.error(f"获取探索历史失败: {str(e)}") return [] finally: conn.close() # 资源管理功能 def get_resource(self, resource_type): """获取特定类型资源""" try: conn = sqlite3.connect(self.environment_db) c = conn.cursor() c.execute('''SELECT name, path, is_active FROM resources WHERE type = ?''', (resource_type,)) resources = [ {"name": item[0], "path": item[1], "is_active": bool(item[2])} for item in c.fetchall() ] return resources except Exception as e: self.logger.error(f"获取资源失败: {str(e)}") return [] finally: conn.close() def activate_resource(self, resource_name): """激活特定资源""" try: conn = sqlite3.connect(self.environment_db) c = conn.cursor() c.execute('''UPDATE resources SET is_active = 0 WHERE type = (SELECT type FROM resources WHERE name = ?)''', (resource_name,)) c.execute('''UPDATE resources SET is_active = 1 WHERE name = ?''', (resource_name,)) conn.commit() self.log_action("resource_activate", f"激活资源: {resource_name}") return True except Exception as e: self.logger.error(f"激活资源失败: {str(e)}") return False finally: conn.close() # 工作区管理功能 def get_workspace_info(self): """获取工作区信息""" return { "workspace": self.workspace_root, "models": self.models_dir, "system": self.system_dir, "cache": self.cache_dir, "temp": self.temp_dir, "python": self.python_dir } # 命令执行功能 def execute_command(self, command): """执行经过授权的系统命令""" if not self._is_authorized("command_exec"): return {"error": "命令执行授权"} try: result = subprocess.run( command, shell=True, capture_output=True, text=True, cwd=self.system_dir, timeout=30 # 防止长时间运行 ) output = { "success": result.returncode == 0, "returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr } self.log_action("command_exec", f"命令: {command[:50]}... 结果: {output['success']}") return output except subprocess.TimeoutExpired: return {"error": "命令执行超时"} except Exception as e: return {"error": str(e)} # 网络搜索功能 def web_search(self, query): """安全网络搜索""" if not self._is_authorized("web_search"): return {"error": "网络搜索授权"} try: # 使用安全的搜索引擎 response = requests.get( f"https://search.brave.com/search?q={requests.utils.quote(query)}", headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" }, timeout=10 ) # 简化结果解析 results = [] # 注意:实际实现需要根据搜索引擎的HTML结构解析 # 这里只是一个示例 results.append({ "title": "示例结果 1", "url": "https://example.com/result1", "content": "这是关于查询的第一个结果..." }) results.append({ "title": "示例结果 2", "url": "https://example.com/result2", "content": "这是关于查询的第二个结果..." }) self.log_action("web_search", f"查询: {query[:30]}... 结果数: {len(results)}") return {"success": True, "results": results} except Exception as e: return {"error": str(e)} # 文件操作功能 def read_file(self, file_path): """读取工作区文件""" full_path = os.path.join(self.workspace_root, file_path) if not self._is_authorized("file_access"): return {"error": "文件访问授权"} if not os.path.abspath(full_path).startswith(os.path.abspath(self.workspace_root)): return {"error": "访问路径超出工作区范围"} try: with open(full_path, 'r', encoding='utf-8') as f: content = f.read() self.log_action("file_read", f"读取文件: {file_path}") return content except Exception as e: return {"error": str(e)} def write_file(self, file_path, content): """入工作区文件""" full_path = os.path.join(self.workspace_root, file_path) if not self._is_authorized("file_access"): return {"error": "文件访问授权"} if not os.path.abspath(full_path).startswith(os.path.abspath(self.workspace_root)): return {"error": "访问路径超出工作区范围"} try: os.makedirs(os.path.dirname(full_path), exist_ok=True) with open(full_path, 'w', encoding='utf-8') as f: f.write(content) self.log_action("file_write", f"入文件: {file_path} ({len(content)} 字节)") return "文件入成功" except Exception as e: return {"error": str(e)} # 辅助功能 def _is_authorized(self, action): """检查操作授权状态""" return self.authorized_actions.get(action, False) def log_action(self, action, details): """记录环境操作日志""" log_entry = { "timestamp": datetime.now().isoformat(), "action": action, "details": details } self.action_log.append(log_entry) # 保存到文件 log_file = os.path.join(self.workspace_root, "environment_actions.log") try: with open(log_file, 'a', encoding='utf-8') as f: f.write(json.dumps(log_entry, ensure_ascii=False) + "\n") except Exception as e: self.logger.error(f"记录日志失败: {str(e)}") # 同时记录到logger self.logger.info(f"{action}: {details}") return True # 使用示例 if __name__ == "__main__": # 配置日志 logging.basicConfig(level=logging.INFO) env = EnvironmentInterface() # 获取工作区信息 print("工作区信息:", json.dumps(env.get_workspace_info(), indent=2, ensure_ascii=False)) # 获取系统信息 print("系统信息:", json.dumps(env.get_system_info(), indent=2, ensure_ascii=False)) # 探索目录 print("工作区内容:", json.dumps(env.explore_directory(), indent=2, ensure_ascii=False)) # 执行命令 print("命令结果:", json.dumps(env.execute_command("echo Hello World"), indent=2, ensure_ascii=False)) # 文件操作 test_file = "test_env_interface.txt" result = env.write_file(test_file, "环境接口测试内容") print("文件入结果:", result) content = env.read_file(test_file) print("文件内容:", content) 两个文件都给你 你看看怎么改
最新发布
08-10
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值