fischer-agentkit/src/agentkit/quality/cascade_detector.py

79 lines
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""CascadeDetector - 独立的级联故障检测工具(委托给 CascadeStateStore"""
from __future__ import annotations
from dataclasses import dataclass
from agentkit.quality.cascade_state_store import (
CascadeStateStore,
InMemoryCascadeStateStore,
)
@dataclass
class CascadeAlert:
"""级联故障告警"""
session_id: str
alert_type: str # "interaction_limit" or "loop_depth"
current_value: int
threshold: int
message: str
class CascadeDetector:
"""检测多 agent 交互中的级联故障"""
def __init__(
self,
max_interactions: int = 10,
max_depth: int = 3,
store: CascadeStateStore | None = None,
):
self._max_interactions = max_interactions
self._max_depth = max_depth
self._store: CascadeStateStore = store or InMemoryCascadeStateStore()
def check_interaction(self, session_id: str) -> CascadeAlert | None:
"""递增并检查交互计数"""
count = self._store.increment_interaction(session_id)
if count > self._max_interactions:
return CascadeAlert(
session_id=session_id,
alert_type="interaction_limit",
current_value=count,
threshold=self._max_interactions,
message=(
f"Session {session_id} exceeded max interactions: "
f"{count} > {self._max_interactions}"
),
)
return None
def check_depth(self, session_id: str, depth: int) -> CascadeAlert | None:
"""检查循环深度"""
self._store.set_depth(session_id, depth)
if depth > self._max_depth:
return CascadeAlert(
session_id=session_id,
alert_type="loop_depth",
current_value=depth,
threshold=self._max_depth,
message=(
f"Session {session_id} exceeded max loop depth: "
f"{depth} > {self._max_depth}"
),
)
return None
def reset(self, session_id: str) -> None:
"""重置某个 session 的计数器"""
self._store.reset(session_id)
def get_stats(self, session_id: str) -> dict[str, int]:
"""获取某个 session 的当前统计"""
return {
"interactions": self._store.get_interaction(session_id),
"depth": self._store.get_depth(session_id),
}