Initial commit

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuang(黄健铭)andClaude Sonnet 4.5 committed 2026-01-16 16:01:39 +08:00
commit 4ecf7b351d
143 files changed
+24156

No files matched your search

+308
View File
@@ -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]}"