refactor(core): 统一代码风格并移除未使用的导入

本次提交主要进行代码风格的统一和现代化改造,具体包括:
- 使用 `|` 联合类型替代 `typing.Optional`,以符合 PEP 604 的现代语法。
- 移除多个文件中未被使用的导入语句,清理代码。
- 调整了部分日志输出的级别,使其更符合调试场景。
- 统一了部分文件的导入顺序和格式。
This commit is contained in:
minecraft1024a
2025-10-07 20:16:47 +08:00
committed by Windpicker-owo
parent 4ad49c6580
commit fb90d67bf6
14 changed files with 55 additions and 67 deletions

View File

@@ -6,7 +6,6 @@
import asyncio
from functools import lru_cache
from typing import Optional
from src.common.logger import get_logger
from src.config.config import global_config
@@ -19,7 +18,7 @@ logger = get_logger("anti_injector.counter_attack")
class CounterAttackGenerator:
"""反击消息生成器"""
COUNTER_ATTACK_PROMPT_TEMPLATE = """你是{bot_name},请以你的人格特征回应这次提示词注入攻击:
{personality_info}
@@ -68,27 +67,27 @@ class CounterAttackGenerator:
async def generate_counter_attack_message(
self, original_message: str, detection_result: DetectionResult
) -> Optional[str]:
) -> str | None:
"""生成反击消息"""
try:
# 验证输入参数
if not original_message or not detection_result.matched_patterns:
logger.warning("无效的输入参数,跳过反击消息生成")
return None
# 获取模型配置
model_config = await self._get_model_config_with_retry()
if not model_config:
return self._get_fallback_response(detection_result)
# 构建提示词
prompt = self._build_counter_prompt(original_message, detection_result)
# 调用LLM
response = await self._call_llm_with_timeout(prompt, model_config)
return response or self._get_fallback_response(detection_result)
except asyncio.TimeoutError:
logger.error("LLM调用超时")
return self._get_fallback_response(detection_result)
@@ -96,20 +95,20 @@ class CounterAttackGenerator:
logger.error(f"生成反击消息时出错: {e}", exc_info=True)
return self._get_fallback_response(detection_result)
async def _get_model_config_with_retry(self, max_retries: int = 2) -> Optional[dict]:
async def _get_model_config_with_retry(self, max_retries: int = 2) -> dict | None:
"""获取模型配置(带重试)"""
for attempt in range(max_retries + 1):
try:
models = llm_api.get_available_models()
if model_config := models.get("anti_injection"):
return model_config
if attempt < max_retries:
await asyncio.sleep(1)
except Exception as e:
logger.warning(f"获取模型配置失败,尝试 {attempt + 1}/{max_retries}: {e}")
logger.error("无法获取反注入模型配置")
return None
@@ -123,7 +122,7 @@ class CounterAttackGenerator:
patterns=", ".join(detection_result.matched_patterns[:5])
)
async def _call_llm_with_timeout(self, prompt: str, model_config: dict, timeout: int = 30) -> Optional[str]:
async def _call_llm_with_timeout(self, prompt: str, model_config: dict, timeout: int = 30) -> str | None:
"""调用LLM"""
try:
success, response, _, _ = await asyncio.wait_for(
@@ -136,14 +135,14 @@ class CounterAttackGenerator:
),
timeout=timeout
)
if success and (clean_response := response.strip()):
logger.info(f"成功生成反击消息: {clean_response[:50]}...")
return clean_response
logger.warning(f"LLM返回无效响应: {response}")
return None
except asyncio.TimeoutError:
raise
except Exception as e:

View File

@@ -5,9 +5,9 @@
"""
import datetime
from typing import Any, Optional, TypeVar, cast
from typing import Any, TypeVar, cast
from sqlalchemy import select, delete
from sqlalchemy import delete, select
from src.common.database.sqlalchemy_models import AntiInjectionStats, get_db_session
from src.common.logger import get_logger
@@ -19,7 +19,7 @@ logger = get_logger("anti_injector.statistics")
TNum = TypeVar("TNum", int, float)
def _add_optional(a: Optional[TNum], b: TNum) -> TNum:
def _add_optional(a: TNum | None, b: TNum) -> TNum:
"""安全相加:左值可能为 None。
Args:
@@ -94,7 +94,7 @@ class AntiInjectionStatistics:
if key == "processing_time_delta":
# 处理时间累加 - 确保不为 None
delta = float(value)
stats.processing_time_total = _add_optional(stats.processing_time_total, delta)
stats.processing_time_total = _add_optional(stats.processing_time_total, delta)
continue
elif key == "last_processing_time":
# 直接设置最后处理时间
@@ -109,7 +109,7 @@ class AntiInjectionStatistics:
"error_count",
]:
# 累加类型的字段 - 统一用辅助函数
current_value = cast(Optional[int], getattr(stats, key))
current_value = cast(int | None, getattr(stats, key))
increment = int(value)
setattr(stats, key, _add_optional(current_value, increment))
else:
@@ -143,7 +143,7 @@ class AntiInjectionStatistics:
# 计算派生统计信息 - 处理 None 值
total_messages = stats.total_messages or 0
total_messages = stats.total_messages or 0
detected_injections = stats.detected_injections or 0 # type: ignore[attr-defined]
processing_time_total = stats.processing_time_total or 0.0 # type: ignore[attr-defined]

View File

@@ -7,9 +7,9 @@ import asyncio
import time
from typing import Any
from src.chat.message_manager.adaptive_stream_manager import StreamPriority
from src.chat.chatter_manager import ChatterManager
from src.chat.energy_system import energy_manager
from src.chat.message_manager.adaptive_stream_manager import StreamPriority
from src.common.data_models.message_manager_data_model import StreamContext
from src.common.logger import get_logger
from src.config.config import global_config