Initial commit
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
commit
4ecf7b351d
143 files changed
+24156
No files matched your search
@@ -0,0 +1,14 @@
|
||||
"""
|
||||
Storage module for RAG evaluation
|
||||
"""
|
||||
|
||||
from .database import DatabaseManager
|
||||
from .history import HistoryManager, HistoryRecord
|
||||
from .trend_analyzer import TrendAnalyzer
|
||||
|
||||
__all__ = [
|
||||
"DatabaseManager",
|
||||
"HistoryManager",
|
||||
"HistoryRecord",
|
||||
"TrendAnalyzer",
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
Database connection and operations module
|
||||
"""
|
||||
|
||||
import pymysql
|
||||
from typing import Optional, Dict, List, Any
|
||||
from contextlib import contextmanager
|
||||
from ..core.config import DatabaseConfig
|
||||
|
||||
|
||||
class DatabaseManager:
|
||||
"""Database connection manager"""
|
||||
|
||||
def __init__(self, config: DatabaseConfig):
|
||||
self.config = config
|
||||
self._connection = None
|
||||
|
||||
def connect(self):
|
||||
"""Establish database connection"""
|
||||
self._connection = pymysql.connect(
|
||||
host=self.config.host,
|
||||
port=self.config.port,
|
||||
user=self.config.user,
|
||||
password=self.config.password,
|
||||
database=self.config.database,
|
||||
charset=self.config.charset,
|
||||
cursorclass=pymysql.cursors.DictCursor
|
||||
)
|
||||
return self._connection
|
||||
|
||||
def close(self):
|
||||
"""Close database connection"""
|
||||
if self._connection:
|
||||
self._connection.close()
|
||||
self._connection = None
|
||||
|
||||
@contextmanager
|
||||
def get_connection(self):
|
||||
"""Get database connection context manager"""
|
||||
conn = self.connect()
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@contextmanager
|
||||
def get_cursor(self):
|
||||
"""Get database cursor context manager"""
|
||||
with self.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
yield cursor
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
cursor.close()
|
||||
|
||||
def execute_query(self, sql: str, params: Optional[tuple] = None) -> List[Dict]:
|
||||
"""Execute SELECT query"""
|
||||
with self.get_cursor() as cursor:
|
||||
cursor.execute(sql, params)
|
||||
return cursor.fetchall()
|
||||
|
||||
def execute_update(self, sql: str, params: Optional[tuple] = None) -> int:
|
||||
"""Execute INSERT/UPDATE/DELETE query"""
|
||||
with self.get_cursor() as cursor:
|
||||
affected_rows = cursor.execute(sql, params)
|
||||
return affected_rows
|
||||
|
||||
def execute_many(self, sql: str, params_list: List[tuple]) -> int:
|
||||
"""Execute batch INSERT/UPDATE"""
|
||||
with self.get_cursor() as cursor:
|
||||
affected_rows = cursor.executemany(sql, params_list)
|
||||
return affected_rows
|
||||
|
||||
def init_schema(self, schema_file: str):
|
||||
"""Initialize database schema from SQL file"""
|
||||
with open(schema_file, 'r', encoding='utf-8') as f:
|
||||
schema_sql = f.read()
|
||||
|
||||
# Split by semicolon and execute each statement
|
||||
statements = [s.strip() for s in schema_sql.split(';') if s.strip()]
|
||||
|
||||
with self.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
for statement in statements:
|
||||
if statement:
|
||||
cursor.execute(statement)
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
raise Exception(f"Failed to initialize schema: {e}")
|
||||
finally:
|
||||
cursor.close()
|
||||
@@ -0,0 +1,308 @@
|
||||
"""
|
||||
Evaluation history management module
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
from dataclasses import dataclass
|
||||
import uuid
|
||||
|
||||
from .database import DatabaseManager
|
||||
from ..report.aggregator import EvaluationSummary
|
||||
|
||||
|
||||
@dataclass
|
||||
class HistoryRecord:
|
||||
"""历史记录"""
|
||||
id: str
|
||||
evaluation_id: str
|
||||
knowledge_base_id: str
|
||||
metric_name: str
|
||||
metric_value: float
|
||||
recorded_at: datetime
|
||||
metadata: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
class HistoryManager:
|
||||
"""评估历史管理器"""
|
||||
|
||||
def __init__(self, db_manager: DatabaseManager):
|
||||
"""
|
||||
初始化历史管理器
|
||||
|
||||
Args:
|
||||
db_manager: 数据库管理器
|
||||
"""
|
||||
self.db = db_manager
|
||||
|
||||
def save_evaluation_history(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
metadata: Optional[Dict[str, Any]] = None
|
||||
) -> None:
|
||||
"""
|
||||
保存评估历史记录
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
metadata: 额外的元数据
|
||||
"""
|
||||
records = []
|
||||
recorded_at = datetime.now()
|
||||
|
||||
# 保存每个指标的历史记录
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
record_id = self._generate_id()
|
||||
biz_seq = self._generate_biz_seq()
|
||||
sys_seq = self._generate_sys_seq()
|
||||
|
||||
records.append((
|
||||
record_id,
|
||||
biz_seq,
|
||||
sys_seq,
|
||||
summary.evaluation_id,
|
||||
summary.knowledge_base_id,
|
||||
metric_name,
|
||||
stats.mean,
|
||||
recorded_at,
|
||||
recorded_at
|
||||
))
|
||||
|
||||
# 批量插入
|
||||
if records:
|
||||
sql = """
|
||||
INSERT INTO evaluation_history
|
||||
(id, biz_seq, sys_seq, evaluation_id, knowledge_base_id,
|
||||
metric_name, metric_value, recorded_at, create_time)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
self.db.execute_many(sql, records)
|
||||
|
||||
def get_history_by_knowledge_base(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
metric_name: Optional[str] = None,
|
||||
limit: int = 100
|
||||
) -> List[HistoryRecord]:
|
||||
"""
|
||||
获取知识库的历史记录
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
metric_name: 指标名称(可选,不指定则返回所有指标)
|
||||
limit: 返回记录数限制
|
||||
|
||||
Returns:
|
||||
历史记录列表
|
||||
"""
|
||||
if metric_name:
|
||||
sql = """
|
||||
SELECT id, evaluation_id, knowledge_base_id, metric_name,
|
||||
metric_value, recorded_at
|
||||
FROM evaluation_history
|
||||
WHERE knowledge_base_id = %s AND metric_name = %s
|
||||
ORDER BY recorded_at DESC
|
||||
LIMIT %s
|
||||
"""
|
||||
params = (knowledge_base_id, metric_name, limit)
|
||||
else:
|
||||
sql = """
|
||||
SELECT id, evaluation_id, knowledge_base_id, metric_name,
|
||||
metric_value, recorded_at
|
||||
FROM evaluation_history
|
||||
WHERE knowledge_base_id = %s
|
||||
ORDER BY recorded_at DESC
|
||||
LIMIT %s
|
||||
"""
|
||||
params = (knowledge_base_id, limit)
|
||||
|
||||
rows = self.db.execute_query(sql, params)
|
||||
|
||||
return [
|
||||
HistoryRecord(
|
||||
id=row['id'],
|
||||
evaluation_id=row['evaluation_id'],
|
||||
knowledge_base_id=row['knowledge_base_id'],
|
||||
metric_name=row['metric_name'],
|
||||
metric_value=row['metric_value'],
|
||||
recorded_at=row['recorded_at']
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def get_history_by_evaluation(
|
||||
self,
|
||||
evaluation_id: str
|
||||
) -> List[HistoryRecord]:
|
||||
"""
|
||||
获取特定评估的历史记录
|
||||
|
||||
Args:
|
||||
evaluation_id: 评估ID
|
||||
|
||||
Returns:
|
||||
历史记录列表
|
||||
"""
|
||||
sql = """
|
||||
SELECT id, evaluation_id, knowledge_base_id, metric_name,
|
||||
metric_value, recorded_at
|
||||
FROM evaluation_history
|
||||
WHERE evaluation_id = %s
|
||||
ORDER BY metric_name
|
||||
"""
|
||||
|
||||
rows = self.db.execute_query(sql, (evaluation_id,))
|
||||
|
||||
return [
|
||||
HistoryRecord(
|
||||
id=row['id'],
|
||||
evaluation_id=row['evaluation_id'],
|
||||
knowledge_base_id=row['knowledge_base_id'],
|
||||
metric_name=row['metric_name'],
|
||||
metric_value=row['metric_value'],
|
||||
recorded_at=row['recorded_at']
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def get_metric_trend(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
metric_name: str,
|
||||
days: int = 30
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
获取指标趋势数据
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
metric_name: 指标名称
|
||||
days: 天数
|
||||
|
||||
Returns:
|
||||
趋势数据列表,每项包含 {timestamp, value, evaluation_id}
|
||||
"""
|
||||
sql = """
|
||||
SELECT evaluation_id, metric_value, recorded_at
|
||||
FROM evaluation_history
|
||||
WHERE knowledge_base_id = %s
|
||||
AND metric_name = %s
|
||||
AND recorded_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
|
||||
ORDER BY recorded_at ASC
|
||||
"""
|
||||
|
||||
rows = self.db.execute_query(sql, (knowledge_base_id, metric_name, days))
|
||||
|
||||
return [
|
||||
{
|
||||
'timestamp': row['recorded_at'].isoformat(),
|
||||
'value': row['metric_value'],
|
||||
'evaluation_id': row['evaluation_id']
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def get_all_metrics_trend(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
days: int = 30
|
||||
) -> Dict[str, List[Dict[str, Any]]]:
|
||||
"""
|
||||
获取所有指标的趋势数据
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
days: 天数
|
||||
|
||||
Returns:
|
||||
按指标名称分组的趋势数据字典
|
||||
"""
|
||||
sql = """
|
||||
SELECT metric_name, evaluation_id, metric_value, recorded_at
|
||||
FROM evaluation_history
|
||||
WHERE knowledge_base_id = %s
|
||||
AND recorded_at >= DATE_SUB(NOW(), INTERVAL %s DAY)
|
||||
ORDER BY metric_name, recorded_at ASC
|
||||
"""
|
||||
|
||||
rows = self.db.execute_query(sql, (knowledge_base_id, days))
|
||||
|
||||
# 按指标分组
|
||||
trends = {}
|
||||
for row in rows:
|
||||
metric_name = row['metric_name']
|
||||
if metric_name not in trends:
|
||||
trends[metric_name] = []
|
||||
|
||||
trends[metric_name].append({
|
||||
'timestamp': row['recorded_at'].isoformat(),
|
||||
'value': row['metric_value'],
|
||||
'evaluation_id': row['evaluation_id']
|
||||
})
|
||||
|
||||
return trends
|
||||
|
||||
def get_latest_metrics(
|
||||
self,
|
||||
knowledge_base_id: str
|
||||
) -> Dict[str, float]:
|
||||
"""
|
||||
获取最新的指标值
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
|
||||
Returns:
|
||||
指标名称到值的字典
|
||||
"""
|
||||
sql = """
|
||||
SELECT h1.metric_name, h1.metric_value
|
||||
FROM evaluation_history h1
|
||||
INNER JOIN (
|
||||
SELECT metric_name, MAX(recorded_at) as max_time
|
||||
FROM evaluation_history
|
||||
WHERE knowledge_base_id = %s
|
||||
GROUP BY metric_name
|
||||
) h2 ON h1.metric_name = h2.metric_name
|
||||
AND h1.recorded_at = h2.max_time
|
||||
WHERE h1.knowledge_base_id = %s
|
||||
"""
|
||||
|
||||
rows = self.db.execute_query(sql, (knowledge_base_id, knowledge_base_id))
|
||||
|
||||
return {
|
||||
row['metric_name']: row['metric_value']
|
||||
for row in rows
|
||||
}
|
||||
|
||||
def delete_old_history(
|
||||
self,
|
||||
days: int = 90
|
||||
) -> int:
|
||||
"""
|
||||
删除旧的历史记录
|
||||
|
||||
Args:
|
||||
days: 保留天数
|
||||
|
||||
Returns:
|
||||
删除的记录数
|
||||
"""
|
||||
sql = """
|
||||
DELETE FROM evaluation_history
|
||||
WHERE recorded_at < DATE_SUB(NOW(), INTERVAL %s DAY)
|
||||
"""
|
||||
|
||||
return self.db.execute_update(sql, (days,))
|
||||
|
||||
def _generate_id(self) -> str:
|
||||
"""生成唯一ID"""
|
||||
return uuid.uuid4().hex
|
||||
|
||||
def _generate_biz_seq(self) -> str:
|
||||
"""生成业务流水号"""
|
||||
return f"BIZ{datetime.now().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:8]}"
|
||||
|
||||
def _generate_sys_seq(self) -> str:
|
||||
"""生成系统流水号"""
|
||||
return f"SYS{datetime.now().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:8]}"
|
||||
@@ -0,0 +1,130 @@
|
||||
-- RAG Evaluation Framework Database Schema
|
||||
-- MySQL 8.0+
|
||||
|
||||
-- 知识库表
|
||||
CREATE TABLE IF NOT EXISTS `knowledge_bases` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`name` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '知识库名称',
|
||||
`description` text COLLATE utf8mb4_bin COMMENT '知识库描述',
|
||||
`file_count` int DEFAULT 0 COMMENT '文件数量',
|
||||
`total_size` bigint DEFAULT 0 COMMENT '总大小(字节)',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='知识库表';
|
||||
|
||||
-- 测评集表
|
||||
CREATE TABLE IF NOT EXISTS `testsets` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`knowledge_base_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '知识库ID',
|
||||
`name` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '测评集名称',
|
||||
`file_path` varchar(512) COLLATE utf8mb4_bin NOT NULL COMMENT 'JSON文件路径',
|
||||
`question_count` int NOT NULL COMMENT '问题数量',
|
||||
`metadata` json COMMENT '元数据(采样策略、问题分布等)',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_knowledge_base_id` (`knowledge_base_id`),
|
||||
KEY `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='测评集表';
|
||||
|
||||
-- 评估任务表
|
||||
CREATE TABLE IF NOT EXISTS `evaluations` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`knowledge_base_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '知识库ID',
|
||||
`testset_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '测评集ID',
|
||||
`status` varchar(20) COLLATE utf8mb4_bin NOT NULL DEFAULT 'pending' COMMENT '状态: pending/running/completed/failed',
|
||||
`config` json COMMENT '评估配置(采样率、并行度等)',
|
||||
`started_at` datetime DEFAULT NULL COMMENT '开始时间',
|
||||
`completed_at` datetime DEFAULT NULL COMMENT '完成时间',
|
||||
`error_message` text COLLATE utf8mb4_bin COMMENT '错误信息',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_knowledge_base_id` (`knowledge_base_id`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='评估任务表';
|
||||
|
||||
-- 评估结果表
|
||||
CREATE TABLE IF NOT EXISTS `evaluation_results` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`evaluation_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '评估任务ID',
|
||||
`question_index` int NOT NULL COMMENT '问题在测评集中的索引',
|
||||
`question_text` text COLLATE utf8mb4_bin NOT NULL COMMENT '问题文本',
|
||||
`context_recall` float DEFAULT NULL COMMENT '上下文召回率',
|
||||
`context_precision` float DEFAULT NULL COMMENT '上下文精确率',
|
||||
`mrr` float DEFAULT NULL COMMENT '平均倒数排名',
|
||||
`ndcg` float DEFAULT NULL COMMENT '归一化折损累计增益',
|
||||
`faithfulness` float DEFAULT NULL COMMENT '忠实度',
|
||||
`answer_relevancy` float DEFAULT NULL COMMENT '答案相关性',
|
||||
`correctness` float DEFAULT NULL COMMENT '正确性',
|
||||
`retrieved_contexts` json COMMENT '检索到的上下文',
|
||||
`generated_answer` text COLLATE utf8mb4_bin COMMENT 'RAG生成的答案',
|
||||
`ground_truth_answer` text COLLATE utf8mb4_bin COMMENT '参考答案',
|
||||
`ground_truth_context` json COMMENT '参考上下文',
|
||||
`retrieval_time_ms` int DEFAULT NULL COMMENT '检索耗时(毫秒)',
|
||||
`generation_time_ms` int DEFAULT NULL COMMENT '生成耗时(毫秒)',
|
||||
`error_message` text COLLATE utf8mb4_bin COMMENT '错误信息',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_evaluation_id` (`evaluation_id`),
|
||||
KEY `idx_question_index` (`question_index`),
|
||||
KEY `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='评估结果表';
|
||||
|
||||
-- 评估汇总表
|
||||
CREATE TABLE IF NOT EXISTS `evaluation_summaries` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`evaluation_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '评估任务ID',
|
||||
`avg_context_recall` float DEFAULT NULL COMMENT '平均上下文召回率',
|
||||
`avg_context_precision` float DEFAULT NULL COMMENT '平均上下文精确率',
|
||||
`avg_mrr` float DEFAULT NULL COMMENT '平均倒数排名',
|
||||
`avg_ndcg` float DEFAULT NULL COMMENT '平均归一化折损累计增益',
|
||||
`avg_faithfulness` float DEFAULT NULL COMMENT '平均忠实度',
|
||||
`avg_answer_relevancy` float DEFAULT NULL COMMENT '平均答案相关性',
|
||||
`avg_correctness` float DEFAULT NULL COMMENT '平均正确性',
|
||||
`overall_score` float DEFAULT NULL COMMENT '整体评分(0-100)',
|
||||
`total_questions` int NOT NULL COMMENT '总问题数',
|
||||
`failed_questions` int DEFAULT 0 COMMENT '失败问题数',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uniq_evaluation_id` (`evaluation_id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_create_time` (`create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='评估汇总表';
|
||||
|
||||
-- 历史趋势表
|
||||
CREATE TABLE IF NOT EXISTS `evaluation_history` (
|
||||
`id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT 'id',
|
||||
`biz_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '业务流水号',
|
||||
`sys_seq` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '系统流水号',
|
||||
`evaluation_id` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '评估任务ID',
|
||||
`metric_name` varchar(64) COLLATE utf8mb4_bin NOT NULL COMMENT '指标名称',
|
||||
`metric_value` float NOT NULL COMMENT '指标值',
|
||||
`recorded_at` datetime NOT NULL COMMENT '记录时间',
|
||||
`create_time` datetime NOT NULL COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_biz_seq` (`biz_seq`),
|
||||
KEY `idx_evaluation_id` (`evaluation_id`),
|
||||
KEY `idx_metric_name` (`metric_name`),
|
||||
KEY `idx_recorded_at` (`recorded_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='历史趋势表';
|
||||
@@ -0,0 +1,395 @@
|
||||
"""
|
||||
Trend analysis module for evaluation history
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional, Tuple
|
||||
from datetime import datetime, timedelta
|
||||
import statistics
|
||||
|
||||
from .history import HistoryManager
|
||||
|
||||
|
||||
class TrendAnalyzer:
|
||||
"""趋势分析器"""
|
||||
|
||||
def __init__(self, history_manager: HistoryManager):
|
||||
"""
|
||||
初始化趋势分析器
|
||||
|
||||
Args:
|
||||
history_manager: 历史管理器
|
||||
"""
|
||||
self.history = history_manager
|
||||
|
||||
def compare_with_baseline(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
current_metrics: Dict[str, float],
|
||||
baseline_evaluation_id: Optional[str] = None
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
"""
|
||||
与基线对比
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
current_metrics: 当前指标值
|
||||
baseline_evaluation_id: 基线评估ID(可选,不指定则使用最新的历史记录)
|
||||
|
||||
Returns:
|
||||
对比结果字典,每个指标包含 {current, baseline, change, change_pct, status}
|
||||
"""
|
||||
# 获取基线指标
|
||||
if baseline_evaluation_id:
|
||||
baseline_records = self.history.get_history_by_evaluation(baseline_evaluation_id)
|
||||
baseline_metrics = {
|
||||
record.metric_name: record.metric_value
|
||||
for record in baseline_records
|
||||
}
|
||||
else:
|
||||
baseline_metrics = self.history.get_latest_metrics(knowledge_base_id)
|
||||
|
||||
# 对比每个指标
|
||||
comparison = {}
|
||||
for metric_name, current_value in current_metrics.items():
|
||||
baseline_value = baseline_metrics.get(metric_name)
|
||||
|
||||
if baseline_value is not None:
|
||||
change = current_value - baseline_value
|
||||
change_pct = (change / baseline_value * 100) if baseline_value != 0 else 0
|
||||
|
||||
# 判断状态
|
||||
if abs(change_pct) < 1:
|
||||
status = 'stable'
|
||||
elif change_pct > 0:
|
||||
status = 'improved'
|
||||
else:
|
||||
status = 'degraded'
|
||||
|
||||
comparison[metric_name] = {
|
||||
'current': current_value,
|
||||
'baseline': baseline_value,
|
||||
'change': change,
|
||||
'change_pct': change_pct,
|
||||
'status': status
|
||||
}
|
||||
else:
|
||||
comparison[metric_name] = {
|
||||
'current': current_value,
|
||||
'baseline': None,
|
||||
'change': None,
|
||||
'change_pct': None,
|
||||
'status': 'new'
|
||||
}
|
||||
|
||||
return comparison
|
||||
|
||||
def analyze_trend(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
metric_name: str,
|
||||
days: int = 30
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
分析指标趋势
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
metric_name: 指标名称
|
||||
days: 分析天数
|
||||
|
||||
Returns:
|
||||
趋势分析结果
|
||||
"""
|
||||
trend_data = self.history.get_metric_trend(
|
||||
knowledge_base_id, metric_name, days
|
||||
)
|
||||
|
||||
if not trend_data:
|
||||
return {
|
||||
'metric': metric_name,
|
||||
'status': 'no_data',
|
||||
'message': '没有历史数据'
|
||||
}
|
||||
|
||||
values = [item['value'] for item in trend_data]
|
||||
|
||||
# 计算统计信息
|
||||
mean_value = statistics.mean(values)
|
||||
std_dev = statistics.stdev(values) if len(values) > 1 else 0
|
||||
min_value = min(values)
|
||||
max_value = max(values)
|
||||
|
||||
# 计算趋势方向
|
||||
trend_direction = self._calculate_trend_direction(values)
|
||||
|
||||
# 检测异常值
|
||||
anomalies = self._detect_anomalies(trend_data, mean_value, std_dev)
|
||||
|
||||
return {
|
||||
'metric': metric_name,
|
||||
'period_days': days,
|
||||
'data_points': len(trend_data),
|
||||
'statistics': {
|
||||
'mean': mean_value,
|
||||
'std_dev': std_dev,
|
||||
'min': min_value,
|
||||
'max': max_value,
|
||||
'latest': values[-1],
|
||||
'earliest': values[0]
|
||||
},
|
||||
'trend': {
|
||||
'direction': trend_direction,
|
||||
'change': values[-1] - values[0],
|
||||
'change_pct': ((values[-1] - values[0]) / values[0] * 100) if values[0] != 0 else 0
|
||||
},
|
||||
'anomalies': anomalies,
|
||||
'data': trend_data
|
||||
}
|
||||
|
||||
def analyze_all_trends(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
days: int = 30
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
"""
|
||||
分析所有指标的趋势
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
days: 分析天数
|
||||
|
||||
Returns:
|
||||
所有指标的趋势分析结果
|
||||
"""
|
||||
trends = self.history.get_all_metrics_trend(knowledge_base_id, days)
|
||||
|
||||
results = {}
|
||||
for metric_name, trend_data in trends.items():
|
||||
if not trend_data:
|
||||
continue
|
||||
|
||||
values = [item['value'] for item in trend_data]
|
||||
|
||||
mean_value = statistics.mean(values)
|
||||
std_dev = statistics.stdev(values) if len(values) > 1 else 0
|
||||
|
||||
trend_direction = self._calculate_trend_direction(values)
|
||||
anomalies = self._detect_anomalies(trend_data, mean_value, std_dev)
|
||||
|
||||
results[metric_name] = {
|
||||
'period_days': days,
|
||||
'data_points': len(trend_data),
|
||||
'statistics': {
|
||||
'mean': mean_value,
|
||||
'std_dev': std_dev,
|
||||
'min': min(values),
|
||||
'max': max(values),
|
||||
'latest': values[-1],
|
||||
'earliest': values[0]
|
||||
},
|
||||
'trend': {
|
||||
'direction': trend_direction,
|
||||
'change': values[-1] - values[0],
|
||||
'change_pct': ((values[-1] - values[0]) / values[0] * 100) if values[0] != 0 else 0
|
||||
},
|
||||
'anomalies': anomalies
|
||||
}
|
||||
|
||||
return results
|
||||
|
||||
def detect_regression(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
current_metrics: Dict[str, float],
|
||||
threshold_pct: float = 5.0
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
检测性能回归
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
current_metrics: 当前指标值
|
||||
threshold_pct: 回归阈值百分比(默认5%)
|
||||
|
||||
Returns:
|
||||
回归问题列表
|
||||
"""
|
||||
comparison = self.compare_with_baseline(
|
||||
knowledge_base_id, current_metrics
|
||||
)
|
||||
|
||||
regressions = []
|
||||
for metric_name, comp in comparison.items():
|
||||
if comp['status'] == 'degraded' and comp['change_pct'] is not None:
|
||||
if abs(comp['change_pct']) >= threshold_pct:
|
||||
regressions.append({
|
||||
'metric': metric_name,
|
||||
'current': comp['current'],
|
||||
'baseline': comp['baseline'],
|
||||
'change_pct': comp['change_pct'],
|
||||
'severity': self._calculate_severity(comp['change_pct'])
|
||||
})
|
||||
|
||||
# 按严重程度排序
|
||||
regressions.sort(key=lambda x: abs(x['change_pct']), reverse=True)
|
||||
|
||||
return regressions
|
||||
|
||||
def generate_trend_summary(
|
||||
self,
|
||||
knowledge_base_id: str,
|
||||
days: int = 30
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
生成趋势摘要
|
||||
|
||||
Args:
|
||||
knowledge_base_id: 知识库ID
|
||||
days: 分析天数
|
||||
|
||||
Returns:
|
||||
趋势摘要
|
||||
"""
|
||||
trends = self.analyze_all_trends(knowledge_base_id, days)
|
||||
|
||||
if not trends:
|
||||
return {
|
||||
'status': 'no_data',
|
||||
'message': '没有历史数据'
|
||||
}
|
||||
|
||||
# 统计各种趋势
|
||||
improving_count = 0
|
||||
stable_count = 0
|
||||
degrading_count = 0
|
||||
total_anomalies = 0
|
||||
|
||||
for metric_name, trend in trends.items():
|
||||
direction = trend['trend']['direction']
|
||||
if direction == 'improving':
|
||||
improving_count += 1
|
||||
elif direction == 'stable':
|
||||
stable_count += 1
|
||||
elif direction == 'degrading':
|
||||
degrading_count += 1
|
||||
|
||||
total_anomalies += len(trend['anomalies'])
|
||||
|
||||
# 整体状态
|
||||
if degrading_count > improving_count:
|
||||
overall_status = 'degrading'
|
||||
elif improving_count > degrading_count:
|
||||
overall_status = 'improving'
|
||||
else:
|
||||
overall_status = 'stable'
|
||||
|
||||
return {
|
||||
'period_days': days,
|
||||
'total_metrics': len(trends),
|
||||
'overall_status': overall_status,
|
||||
'metrics_improving': improving_count,
|
||||
'metrics_stable': stable_count,
|
||||
'metrics_degrading': degrading_count,
|
||||
'total_anomalies': total_anomalies,
|
||||
'details': trends
|
||||
}
|
||||
|
||||
def _calculate_trend_direction(
|
||||
self,
|
||||
values: List[float]
|
||||
) -> str:
|
||||
"""
|
||||
计算趋势方向
|
||||
|
||||
使用简单线性回归的斜率判断趋势
|
||||
|
||||
Args:
|
||||
values: 值列表
|
||||
|
||||
Returns:
|
||||
趋势方向: 'improving', 'stable', 'degrading'
|
||||
"""
|
||||
if len(values) < 2:
|
||||
return 'stable'
|
||||
|
||||
# 计算线性回归斜率
|
||||
n = len(values)
|
||||
x = list(range(n))
|
||||
x_mean = statistics.mean(x)
|
||||
y_mean = statistics.mean(values)
|
||||
|
||||
numerator = sum((x[i] - x_mean) * (values[i] - y_mean) for i in range(n))
|
||||
denominator = sum((x[i] - x_mean) ** 2 for i in range(n))
|
||||
|
||||
if denominator == 0:
|
||||
return 'stable'
|
||||
|
||||
slope = numerator / denominator
|
||||
|
||||
# 判断趋势
|
||||
if abs(slope) < 0.001: # 斜率接近0
|
||||
return 'stable'
|
||||
elif slope > 0:
|
||||
return 'improving'
|
||||
else:
|
||||
return 'degrading'
|
||||
|
||||
def _detect_anomalies(
|
||||
self,
|
||||
trend_data: List[Dict[str, Any]],
|
||||
mean: float,
|
||||
std_dev: float,
|
||||
threshold: float = 2.0
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
检测异常值
|
||||
|
||||
使用标准差方法检测异常值
|
||||
|
||||
Args:
|
||||
trend_data: 趋势数据
|
||||
mean: 平均值
|
||||
std_dev: 标准差
|
||||
threshold: 异常阈值(标准差倍数)
|
||||
|
||||
Returns:
|
||||
异常值列表
|
||||
"""
|
||||
if std_dev == 0:
|
||||
return []
|
||||
|
||||
anomalies = []
|
||||
for item in trend_data:
|
||||
value = item['value']
|
||||
z_score = abs((value - mean) / std_dev)
|
||||
|
||||
if z_score > threshold:
|
||||
anomalies.append({
|
||||
'timestamp': item['timestamp'],
|
||||
'value': value,
|
||||
'z_score': z_score,
|
||||
'evaluation_id': item['evaluation_id']
|
||||
})
|
||||
|
||||
return anomalies
|
||||
|
||||
def _calculate_severity(self, change_pct: float) -> str:
|
||||
"""
|
||||
计算回归严重程度
|
||||
|
||||
Args:
|
||||
change_pct: 变化百分比
|
||||
|
||||
Returns:
|
||||
严重程度: 'critical', 'high', 'medium', 'low'
|
||||
"""
|
||||
abs_change = abs(change_pct)
|
||||
|
||||
if abs_change >= 20:
|
||||
return 'critical'
|
||||
elif abs_change >= 10:
|
||||
return 'high'
|
||||
elif abs_change >= 5:
|
||||
return 'medium'
|
||||
else:
|
||||
return 'low'
|
||||
Reference in new issue
Block a user