Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(symphony): Symphony增加能力评估功能

lin-xiaoyud2496da8e2cf
diff --git a/jiuwenswarm/symphony/evaluation/__init__.py b/jiuwenswarm/symphony/evaluation/__init__.py
new file mode 100644
index 0000000000..5eea04fd29
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/__init__.py
@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+"""Unified public API for Agent and Skill evaluation."""
+
+from jiuwenswarm.symphony.evaluation.aggregation import MetricAccumulator
+from jiuwenswarm.symphony.evaluation.artifacts import write_quality_report
+from jiuwenswarm.symphony.evaluation.evaluators import (
+ AccuracyEvaluator,
+ BaseEvaluator,
+ CompletenessEvaluator,
+ ComplianceEvaluator,
+ ComplianceRule,
+ LatencyEvaluator,
+ LatencyScenario,
+ LatencyScenarioClassifier,
+ LatencyScenarioResult,
+ SuccessRateEvaluator,
+)
+from jiuwenswarm.symphony.evaluation.interfaces import EvaluationLLM
+from jiuwenswarm.symphony.evaluation.models import (
+ AssertionResult,
+ ComplianceSeverity,
+ EvaluationCase,
+ Latency,
+ MetricResult,
+ QualityResult,
+ Window,
+ to_json_safe,
+)
+from jiuwenswarm.symphony.evaluation.suite import (
+ EvaluationAccumulator,
+ EvaluationSuite,
+)
+from jiuwenswarm.symphony.fingerprint.models import (
+ ArtifactSpec,
+ Fingerprint,
+ ParameterSpec,
+)
+
+__all__ = [
+ "AccuracyEvaluator",
+ "ArtifactSpec",
+ "AssertionResult",
+ "BaseEvaluator",
+ "ComplianceEvaluator",
+ "ComplianceRule",
+ "ComplianceSeverity",
+ "CompletenessEvaluator",
+ "EvaluationAccumulator",
+ "EvaluationCase",
+ "EvaluationLLM",
+ "EvaluationSuite",
+ "Fingerprint",
+ "Latency",
+ "LatencyEvaluator",
+ "LatencyScenario",
+ "LatencyScenarioClassifier",
+ "LatencyScenarioResult",
+ "MetricAccumulator",
+ "MetricResult",
+ "ParameterSpec",
+ "QualityResult",
+ "SuccessRateEvaluator",
+ "Window",
+ "write_quality_report",
+ "to_json_safe",
+]
diff --git a/jiuwenswarm/symphony/evaluation/aggregation.py b/jiuwenswarm/symphony/evaluation/aggregation.py
new file mode 100644
index 0000000000..71cad25bb3
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/aggregation.py
@@ -0,0 +1,99 @@
+# -*- coding: utf-8 -*-
+"""Metric grading and result aggregation primitives."""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from typing import Any, Iterable
+
+from jiuwenswarm.symphony.evaluation.models import (
+ MetricLevel,
+ MetricResult,
+ Window,
+)
+
+
+def score_level(score: float, thresholds: tuple[float, float, float]) -> MetricLevel:
+ """Map ascending pass/good/excellent thresholds to a level."""
+
+ pass_threshold, good_threshold, excellent_threshold = thresholds
+ if score >= excellent_threshold:
+ return "excellent"
+ if score >= good_threshold:
+ return "good"
+ if score >= pass_threshold:
+ return "pass"
+ return "fail"
+
+
+class MetricAccumulator:
+ """Aggregate one metric, grouped by fingerprint identity."""
+
+ def __init__(
+ self,
+ metric: str,
+ window: Window | None = None,
+ aggregation_thresholds: tuple[float, float, float] = (0.6, 0.8, 0.9),
+ ) -> None:
+ self.metric = metric
+ self.window = window
+ self.aggregation_thresholds = aggregation_thresholds
+ self._results: list[MetricResult] = []
+
+ def add(self, result: MetricResult) -> "MetricAccumulator":
+ if result.metric != self.metric:
+ raise ValueError(f"Expected metric {self.metric!r}, got {result.metric!r}.")
+ self._results.append(result)
+ return self
+
+ def extend(self, results: Iterable[MetricResult]) -> "MetricAccumulator":
+ for result in results:
+ self.add(result)
+ return self
+
+ def aggregate(self) -> list[MetricResult]:
+ grouped: dict[tuple[str, str, str], list[MetricResult]] = defaultdict(list)
+ for result in self._results:
+ grouped[(result.type, result.id, result.version)].append(result)
+ return [
+ self._aggregate_group(results)
+ for _, results in sorted(grouped.items(), key=lambda item: item[0])
+ ]
+
+ def _aggregate_group(self, results: list[MetricResult]) -> MetricResult:
+ applicable = [result for result in results if result.score is not None]
+ template = results[0]
+ if not applicable:
+ return MetricResult(
+ metric=self.metric,
+ type=template.type,
+ id=template.id,
+ version=template.version,
+ event_time=None,
+ score=None,
+ level="not_applicable",
+ reason="",
+ metrics={"result_count": 0},
+ )
+ score = sum(result.score or 0 for result in applicable) / len(applicable)
+ if self.metric == "success_rate":
+ level: MetricLevel = "excellent" if score >= 0.999 else "fail"
+ else:
+ level = score_level(score, self.aggregation_thresholds)
+ metrics = self._aggregate_metrics(applicable)
+ metrics["result_count"] = len(applicable)
+ return MetricResult(
+ metric=self.metric,
+ type=template.type,
+ id=template.id,
+ version=template.version,
+ event_time=None,
+ score=score,
+ level=level,
+ reason="",
+ metrics=metrics,
+ )
+
+ @staticmethod
+ def _aggregate_metrics(results: list[MetricResult]) -> dict[str, Any]:
+ return {}
diff --git a/jiuwenswarm/symphony/evaluation/artifacts.py b/jiuwenswarm/symphony/evaluation/artifacts.py
new file mode 100644
index 0000000000..95678f0c0f
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/artifacts.py
@@ -0,0 +1,337 @@
+# -*- coding: utf-8 -*-
+"""Persist evaluation quality alongside public fingerprint fields."""
+
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+from pathlib import Path
+from typing import Any, Iterable
+
+from jiuwenswarm.symphony.evaluation.models import (
+ QualityResult,
+ Window,
+ to_json_safe,
+)
+from jiuwenswarm.symphony.fingerprint.models import Fingerprint
+
+
+CORE_METRICS = (
+ "success_rate",
+ "latency",
+ "accuracy",
+ "completeness",
+ "compliance",
+)
+REPORT_METRIC_BY_CORE = {
+ "success_rate": "success_rate",
+ "latency": "latency",
+ "accuracy": "accuracy",
+ "completeness": "fluency",
+ "compliance": "compliance",
+}
+REPORT_METRICS = tuple(REPORT_METRIC_BY_CORE.values())
+METRIC_NAMES = {
+ "success_rate": "响应完成率",
+ "latency": "响应时延",
+ "accuracy": "准确性",
+ "fluency": "交互流畅性",
+ "compliance": "结构规范性",
+}
+
+
+def _identity(item: dict[str, Any]) -> tuple[str, str, str]:
+ return (
+ str(item.get("type", "")),
+ str(item.get("id", "")),
+ str(item.get("version", "")),
+ )
+
+
+def _public_fingerprint(fingerprint: Fingerprint) -> dict[str, Any]:
+ return {
+ "type": fingerprint.type,
+ "id": fingerprint.id,
+ "name": fingerprint.name,
+ "description": fingerprint.description,
+ "version": fingerprint.version,
+ "inputs": [item.to_dict() for item in fingerprint.inputs],
+ "outputs": [item.to_dict() for item in fingerprint.outputs],
+ }
+
+
+def _distribution(value: Any) -> tuple[Any, Any, Any]:
+ if isinstance(value, dict):
+ return value.get("avg"), value.get("p95"), value.get("p99")
+ return value, value, value
+
+
+def _latency_metrics(metrics: dict[str, Any]) -> dict[str, Any]:
+ flat_names = (
+ "avg_ttft",
+ "p95_ttft",
+ "p99_ttft",
+ "avg_e2e",
+ "p95_e2e",
+ "p99_e2e",
+ )
+ if any(name in metrics for name in flat_names):
+ return {name: metrics.get(name) for name in flat_names}
+ ttft_avg, ttft_p95, ttft_p99 = _distribution(metrics.get("ttft"))
+ e2e_avg, e2e_p95, e2e_p99 = _distribution(metrics.get("e2e"))
+ return {
+ "avg_ttft": ttft_avg,
+ "p95_ttft": ttft_p95,
+ "p99_ttft": ttft_p99,
+ "avg_e2e": e2e_avg,
+ "p95_e2e": e2e_p95,
+ "p99_e2e": e2e_p99,
+ }
+
+
+def _quality_payload(result: QualityResult) -> dict[str, Any]:
+ if set(result.metrics) != set(CORE_METRICS):
+ raise ValueError("QualityResult must contain the five standard metrics.")
+ result_identity = (result.type, result.id, result.version)
+ metrics: dict[str, Any] = {}
+ for core_name in CORE_METRICS:
+ report_name = REPORT_METRIC_BY_CORE[core_name]
+ metric = result.metrics[core_name]
+ if metric.metric != core_name:
+ raise ValueError(
+ f"MetricResult metric {metric.metric!r} must match its "
+ f"mapping key {core_name!r}."
+ )
+ metric_identity = (metric.type, metric.id, metric.version)
+ if metric_identity != result_identity:
+ raise ValueError(
+ "MetricResult identity must match QualityResult identity: "
+ f"{metric_identity!r} != {result_identity!r}."
+ )
+ metric_details = dict(metric.metrics)
+ metric_details.pop("result_count", None)
+ metrics[report_name] = {
+ "name": METRIC_NAMES[report_name],
+ "score": metric.score,
+ "level": metric.level,
+ "result_count": int(
+ metric.metrics.get("result_count", result.result_count)
+ ),
+ "metrics": (
+ _latency_metrics(metric_details)
+ if core_name == "latency"
+ else metric_details
+ ),
+ }
+ if core_name == "latency":
+ metrics[report_name]["scenario"] = metric.metrics.get("scenario")
+ return metrics
+
+
+def _clean_mapping(value: Any) -> Any:
+ if isinstance(value, dict):
+ excluded = {
+ "quality_score",
+ "static_data",
+ "assertions",
+ "evidence",
+ }
+ cleaned = {}
+ for key, item in value.items():
+ if key not in excluded:
+ cleaned[key] = _clean_mapping(item)
+ return cleaned
+ if isinstance(value, list):
+ return [_clean_mapping(item) for item in value]
+ return value
+
+
+def _sanitize_existing_metric(name: str, value: Any) -> dict[str, Any] | None:
+ if not isinstance(value, dict):
+ return None
+ required = {"score", "level", "result_count"}
+ if not required <= set(value):
+ return None
+ metric_details = _clean_mapping(value.get("metrics", {}))
+ if isinstance(metric_details, dict):
+ metric_details.pop("result_count", None)
+ cleaned = {
+ "name": METRIC_NAMES[name],
+ "score": value["score"],
+ "level": value["level"],
+ "result_count": value["result_count"],
+ "metrics": metric_details,
+ }
+ if name == "latency":
+ raw_metrics = value.get("metrics", {})
+ fallback_scenario = (
+ raw_metrics.get("scenario") if isinstance(raw_metrics, dict) else None
+ )
+ cleaned["scenario"] = value.get("scenario", fallback_scenario)
+ cleaned["metrics"] = _latency_metrics(cleaned["metrics"])
+ return cleaned
+
+
+def _sanitize_existing_quality(value: Any) -> dict[str, Any] | None:
+ if not isinstance(value, dict):
+ return None
+ candidate = value.get("metrics", value)
+ if not isinstance(candidate, dict) or not set(REPORT_METRICS) <= set(candidate):
+ return None
+ cleaned = {
+ name: _sanitize_existing_metric(name, candidate[name])
+ for name in REPORT_METRICS
+ }
+ if any(item is None for item in cleaned.values()):
+ return None
+ return cleaned
+
+
+def _sanitize_existing(item: dict[str, Any]) -> dict[str, Any]:
+ cleaned = {}
+ public_fields = (
+ "type",
+ "id",
+ "name",
+ "description",
+ "version",
+ "inputs",
+ "outputs",
+ )
+ for key in public_fields:
+ if key in item:
+ cleaned[key] = item[key]
+ quality = _sanitize_existing_quality(item.get("quality"))
+ if quality is not None:
+ cleaned["quality"] = quality
+ return _clean_mapping(cleaned)
+
+
+def _effective_window(
+ results: list[QualityResult], explicit: Window | None
+) -> Window | None:
+ if explicit is not None:
+ if any(result.window != explicit for result in results):
+ raise ValueError("QualityResult windows must match the explicit window.")
+ return explicit
+ if not results:
+ return None
+ inferred = results[0].window
+ if any(result.window != inferred for result in results[1:]):
+ raise ValueError("QualityResult windows must be consistent.")
+ return inferred
+
+
+def _window_payload(value: Any) -> dict[str, Any] | None:
+ if value is None:
+ return None
+ if not isinstance(value, dict):
+ raise ValueError("fingerprints.json window must be an object or null.")
+ return {
+ "start": value.get("start"),
+ "end": value.get("end"),
+ "label": value.get("label"),
+ }
+
+
+def write_quality_report(
+ path: str | Path,
+ fingerprints: Iterable[Fingerprint],
+ quality_results: Iterable[QualityResult],
+ window: Window | None = None,
+) -> Path:
+ """Atomically merge quality results into a public ``fingerprints.json``.
+
+ Objects are joined by ``(type, id, version)``. Existing unrelated objects
+ remain in the report, while evaluation-only private static data is omitted.
+ """
+
+ target = Path(path)
+ if target.suffix.lower() != ".json":
+ target = target / "fingerprints.json"
+ target.parent.mkdir(parents=True, exist_ok=True)
+
+ supplied = {
+ (item.type, item.id, item.version): _public_fingerprint(item)
+ for item in fingerprints
+ }
+ quality_items = list(quality_results)
+ effective_window = _effective_window(quality_items, window)
+ effective_window_payload = effective_window.to_dict() if effective_window else None
+ quality_by_identity = {
+ (item.type, item.id, item.version): item for item in quality_items
+ }
+ missing = sorted(set(quality_by_identity) - set(supplied))
+ if missing:
+ raise ValueError(
+ "Quality results have no matching fingerprint: "
+ + ", ".join("/".join(identity) for identity in missing)
+ )
+
+ existing: list[dict[str, Any]] = []
+ existing_window_payload: dict[str, Any] | None = None
+ if target.exists():
+ payload = json.loads(target.read_text(encoding="utf-8"))
+ if not isinstance(payload, dict):
+ raise ValueError("fingerprints.json must contain a JSON object.")
+ existing_window_payload = _window_payload(payload.get("window"))
+ raw_fingerprints = payload.get("fingerprints", [])
+ if not isinstance(raw_fingerprints, list):
+ raise ValueError("fingerprints.json must contain a fingerprints list.")
+ existing = [
+ _sanitize_existing(item)
+ for item in raw_fingerprints
+ if isinstance(item, dict)
+ ]
+ if existing_window_payload != effective_window_payload:
+ for item in existing:
+ item.pop("quality", None)
+
+ merged = {_identity(item): item for item in existing}
+ for identity, item in supplied.items():
+ previous_quality = merged.get(identity, {}).get("quality")
+ merged[identity] = item
+ if identity in quality_by_identity:
+ merged[identity]["quality"] = _quality_payload(
+ quality_by_identity[identity]
+ )
+ elif previous_quality is not None:
+ merged[identity]["quality"] = previous_quality
+
+ report = to_json_safe(
+ _clean_mapping(
+ {
+ "window": effective_window_payload,
+ "fingerprints": [merged[key] for key in sorted(merged)],
+ }
+ )
+ )
+ descriptor: int | None = None
+ temporary_path: Path | None = None
+ try:
+ descriptor, temporary_name = tempfile.mkstemp(
+ prefix=f".{target.name}.", suffix=".tmp", dir=target.parent
+ )
+ temporary_path = Path(temporary_name)
+ stream = os.fdopen(descriptor, "w", encoding="utf-8", newline="\n")
+ descriptor = None
+ with stream:
+ json.dump(
+ report,
+ stream,
+ ensure_ascii=False,
+ indent=2,
+ allow_nan=False,
+ )
+ stream.write("\n")
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary_path, target)
+ temporary_path = None
+ finally:
+ if descriptor is not None:
+ os.close(descriptor)
+ if temporary_path is not None:
+ temporary_path.unlink(missing_ok=True)
+ return target
diff --git a/jiuwenswarm/symphony/evaluation/evaluators/__init__.py b/jiuwenswarm/symphony/evaluation/evaluators/__init__.py
new file mode 100644
index 0000000000..060947f466
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/evaluators/__init__.py
@@ -0,0 +1,33 @@
+"""Single-metric evaluators used by the evaluation facade and Suite."""
+
+from jiuwenswarm.symphony.evaluation.evaluators.accuracy import AccuracyEvaluator
+from jiuwenswarm.symphony.evaluation.evaluators.base import BaseEvaluator
+from jiuwenswarm.symphony.evaluation.evaluators.completeness import (
+ CompletenessEvaluator,
+)
+from jiuwenswarm.symphony.evaluation.evaluators.compliance import (
+ ComplianceEvaluator,
+ ComplianceRule,
+)
+from jiuwenswarm.symphony.evaluation.evaluators.latency import (
+ LatencyEvaluator,
+ LatencyScenario,
+ LatencyScenarioClassifier,
+ LatencyScenarioResult,
+)
+from jiuwenswarm.symphony.evaluation.evaluators.success_rate import (
+ SuccessRateEvaluator,
+)
+
+__all__ = [
+ "AccuracyEvaluator",
+ "BaseEvaluator",
+ "CompletenessEvaluator",
+ "ComplianceEvaluator",
+ "ComplianceRule",
+ "LatencyEvaluator",
+ "LatencyScenario",
+ "LatencyScenarioClassifier",
+ "LatencyScenarioResult",
+ "SuccessRateEvaluator",
+]
diff --git a/jiuwenswarm/symphony/evaluation/evaluators/accuracy.py b/jiuwenswarm/symphony/evaluation/evaluators/accuracy.py
new file mode 100644
index 0000000000..d12a14b8bc
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/evaluators/accuracy.py
@@ -0,0 +1,34 @@
+"""LLM-based execution accuracy evaluator."""
+
+from jiuwenswarm.symphony.evaluation.evaluators.base import LLMScoreEvaluator
+
+
+class AccuracyEvaluator(LLMScoreEvaluator):
+ metric = "accuracy"
+ thresholds = (0.90, 0.95, 0.99)
+ aggregation_thresholds = thresholds
+ rubric = (
+ "准确性二值评分标准:\n"
+ "优秀(score=1,满足以下所有条件):\n"
+ "- 无事实性错误,核心信息准确。\n"
+ "- 完全符合客观事实,无任何事实性错误。\n"
+ "- 逻辑严密,推理严谨,无逻辑谬误。\n"
+ "- 符合行业规范/专业规范,表述专业。\n"
+ "- 新知识/新产品场景:当回答涉及新知识、新产品、新功能等内容时,"
+ "即使评估模型的历史训练数据中未包含这些信息,只要回答逻辑合理、"
+ "符合用户需求、表述清晰,也应判断为准确回答。\n"
+ "不及格(score=0,满足以下条件之一):\n"
+ "- 存在事实性错误,与客观事实不符。\n"
+ "- 存在逻辑谬误,推理过程断裂。\n"
+ "- 存在专业偏差,违背行业标准/专业规范。\n"
+ "- 输出内容不可用,可能误导用户。\n"
+ "补充规则:\n"
+ "1. 事实核查:以有无事实错误为首要判断标准,检查执行结果中是否存在"
+ "事实性错误。\n"
+ "2. 逻辑验证:检查推理过程是否严密,是否存在逻辑谬误。\n"
+ "3. 专业规范:评估是否符合行业规范/专业规范。\n"
+ "4. 新知识处理:对于涉及新知识、新产品、新功能的内容,评估其逻辑"
+ "合理性和表述清晰度。\n"
+ "注意事项:如果数据不完整,应在 reason 中说明;核心评估重点是有无"
+ "事实错误,只要存在事实性错误即判定为不及格。"
+ )
diff --git a/jiuwenswarm/symphony/evaluation/evaluators/base.py b/jiuwenswarm/symphony/evaluation/evaluators/base.py
new file mode 100644
index 0000000000..30d8602087
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/evaluators/base.py
@@ -0,0 +1,119 @@
+# -*- coding: utf-8 -*-
+"""Common evaluator behavior, including shared LLM scoring."""
+
+from __future__ import annotations
+
+import json
+from abc import ABC, abstractmethod
+from typing import Any, Iterable, Sequence
+
+from jiuwenswarm.symphony.evaluation.aggregation import (
+ MetricAccumulator,
+ score_level,
+)
+from jiuwenswarm.symphony.evaluation.interfaces import EvaluationLLM
+from jiuwenswarm.symphony.evaluation.models import (
+ EvaluationCase,
+ MetricLevel,
+ MetricResult,
+ Window,
+)
+
+
+class BaseEvaluator(ABC):
+ """Common synchronous interface implemented by every metric evaluator."""
+
+ metric: str
+ aggregation_thresholds: tuple[float, float, float] = (0.6, 0.8, 0.9)
+
+ @abstractmethod
+ def evaluate(self, case: EvaluationCase) -> MetricResult:
+ """Evaluate one complete execution case."""
+
+ def evaluate_batch(self, cases: Iterable[EvaluationCase]) -> list[MetricResult]:
+ return [self.evaluate(case) for case in cases]
+
+ def new_accumulator(self, window: Window | None = None) -> MetricAccumulator:
+ return MetricAccumulator(
+ self.metric,
+ window,
+ aggregation_thresholds=self.aggregation_thresholds,
+ )
+
+ def result(
+ self,
+ case: EvaluationCase,
+ score: float | None,
+ level: MetricLevel,
+ reason: str,
+ metrics: dict[str, Any] | None = None,
+ ) -> MetricResult:
+ return MetricResult(
+ metric=self.metric,
+ type=case.fingerprint.type,
+ id=case.fingerprint.id,
+ version=case.fingerprint.version,
+ event_time=case.event_time,
+ score=score,
+ level=level,
+ reason=reason,
+ metrics=dict(metrics or {}),
+ )
+
+ def not_applicable(self, case: EvaluationCase, reason: str) -> MetricResult:
+ return self.result(case, None, "not_applicable", reason)
+
+
+class LLMScoreEvaluator(BaseEvaluator):
+ """Shared fail-soft scoring flow for LLM-based metrics."""
+
+ thresholds: tuple[float, float, float]
+ rubric: str
+
+ def __init__(self, llm: EvaluationLLM | None = None) -> None:
+ self.llm = llm
+
+ def evaluate(self, case: EvaluationCase) -> MetricResult:
+ if self.llm is None:
+ return self.not_applicable(case, "An evaluation LLM is not configured.")
+ if not case.input_contents:
+ return self.not_applicable(case, "The message has no user input.")
+ if case.final_output is None:
+ return self.not_applicable(case, "The message has no assistant output.")
+ try:
+ responses = self.llm.chat([{"role": "user", "content": self._prompt(case)}])
+ payload = self._parse(responses)
+ except Exception as exc:
+ return self.not_applicable(case, f"LLM evaluation failed: {exc}")
+ score = payload.get("score")
+ if isinstance(score, bool) or not isinstance(score, (int, float)):
+ return self.not_applicable(case, "LLM response has no numeric score.")
+ score = float(score)
+ if score not in {0.0, 1.0}:
+ return self.not_applicable(case, "LLM score must be either 0 or 1.")
+ reason = payload.get("reason")
+ if not isinstance(reason, str):
+ return self.not_applicable(case, "LLM response has no textual reason.")
+ return self.result(case, score, score_level(score, self.thresholds), reason)
+
+ def _prompt(self, case: EvaluationCase) -> str:
+ payload = {
+ "fingerprint": case.fingerprint.to_dict(),
+ "message": case.message,
+ }
+ return (
+ f"{self.rubric}\n\n"
+ "输出要求:score 只能是数字 0 或 1;reason 只写一句简短理由,"
+ "指出决定性证据,不复述评分标准,不虚构依据。不要输出思考过程,"
+ "只返回 JSON:{\"score\": 0 或 1, \"reason\": \"理由\"}。\n"
+ f"Evaluation data:\n{json.dumps(payload, ensure_ascii=False, default=str)}"
+ )
+
+ @staticmethod
+ def _parse(responses: Sequence[str]) -> dict[str, Any]:
+ if not responses or not isinstance(responses[0], str):
+ raise ValueError("LLM returned no response.")
+ payload = json.loads(responses[0])
+ if not isinstance(payload, dict):
+ raise ValueError("LLM response is not a JSON object.")
+ return payload
diff --git a/jiuwenswarm/symphony/evaluation/evaluators/completeness.py b/jiuwenswarm/symphony/evaluation/evaluators/completeness.py
new file mode 100644
index 0000000000..1d9f4647a4
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/evaluators/completeness.py
@@ -0,0 +1,34 @@
+"""LLM-based execution completeness evaluator."""
+
+from jiuwenswarm.symphony.evaluation.evaluators.base import LLMScoreEvaluator
+
+
+class CompletenessEvaluator(LLMScoreEvaluator):
+ metric = "completeness"
+ thresholds = (0.60, 0.80, 0.90)
+ aggregation_thresholds = thresholds
+ rubric = (
+ "完整性二值评分标准:\n"
+ "优秀(score=1,满足以下所有条件):\n"
+ "- 智能体完整执行了用户请求的技能,提供了完整的功能或服务。\n"
+ "- 智能体在多步骤任务中完成了完整的功能流程,从识别意图到执行技能的"
+ "完整过程。\n"
+ "- 智能体声称具备的技能与实际执行能力一致,能够完整满足用户需求。\n"
+ "不及格(score=0,满足以下条件之一):\n"
+ "- 智能体未能提供用户请求的功能或服务,如查询航班、预订服务等核心"
+ "功能无法实现。\n"
+ "- 智能体未能完整执行用户请求的技能,如用户请求“导航到XXX”,"
+ "智能体仅提供路径规划但未启动导航,判定为不具备完整导航能力。\n"
+ "- 多步骤任务场景:智能体声称具备某项技能,如订票、导航、预订、支付"
+ "等,但在执行过程中仅完成了部分步骤,如查询、规划,未完成完整的功能"
+ "流程,判定为不具备完整技能能力。\n"
+ "- 智能体部分执行了用户请求的技能,但未完成完整流程。\n"
+ "补充规则:\n"
+ "1. 功能执行:检查智能体是否完整执行了用户请求的技能。\n"
+ "2. 流程完整性:评估执行流程是否完整,从识别意图到执行技能的完整"
+ "过程。\n"
+ "3. 多步骤任务:在多步骤任务场景中,检查是否完成了完整的功能流程。\n"
+ "4. 技能一致性:评估智能体声称具备的技能与实际执行能力是否一致。\n"
+ "注意事项:如果数据不完整,应在 reason 中说明;重点关注技能描述中"
+ "明确提到的步骤和要求,特别关注多步骤任务场景中的功能流程完整性。"
+ )
diff --git a/jiuwenswarm/symphony/evaluation/evaluators/compliance.py b/jiuwenswarm/symphony/evaluation/evaluators/compliance.py
new file mode 100644
index 0000000000..451c7e1d33
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/evaluators/compliance.py
@@ -0,0 +1,108 @@
+"""Deterministic static compliance evaluator and aggregation."""
+
+from __future__ import annotations
+
+from dataclasses import replace
+from typing import Iterable, Protocol
+
+from jiuwenswarm.symphony.evaluation.aggregation import MetricAccumulator
+from jiuwenswarm.symphony.evaluation.evaluators.base import BaseEvaluator
+from jiuwenswarm.symphony.evaluation.models import (
+ AssertionResult,
+ ComplianceSeverity,
+ EvaluationCase,
+ MetricResult,
+ Window,
+)
+from jiuwenswarm.symphony.fingerprint.models import Fingerprint
+
+
+class ComplianceRule(Protocol):
+ """Deterministic static compliance rule supplied by a business adapter."""
+
+ code: str
+ severity: ComplianceSeverity
+
+ def evaluate(self, fingerprint: Fingerprint) -> AssertionResult:
+ """Evaluate one fingerprint against this rule."""
+ ...
+
+
+class ComplianceEvaluator(BaseEvaluator):
+ metric = "compliance"
+
+ def __init__(self, rules: Iterable[ComplianceRule] = ()) -> None:
+ self.rules = list(rules)
+ for rule in self.rules:
+ if rule.severity not in {"light", "major", "hard"}:
+ raise ValueError(
+ f"Unsupported compliance severity for rule {rule.code!r}: "
+ f"{rule.severity!r}"
+ )
+
+ def evaluate(self, case: EvaluationCase) -> MetricResult:
+ if not self.rules:
+ return self.not_applicable(case, "No compliance rules are configured.")
+ assertions: list[AssertionResult] = []
+ for rule in self.rules:
+ try:
+ severity = rule.severity
+ if severity not in {"light", "major", "hard"}:
+ raise ValueError(f"Unsupported compliance severity: {severity!r}")
+ evaluated = rule.evaluate(case.fingerprint)
+ if not isinstance(evaluated, AssertionResult):
+ raise TypeError("Compliance rule must return AssertionResult.")
+ assertion = replace(
+ evaluated,
+ code=rule.code,
+ severity=severity,
+ )
+ except Exception as exc:
+ assertion = AssertionResult(
+ code=rule.code,
+ passed=False,
+ severity="hard",
+ reason=f"Compliance rule raised an exception: {exc}",
+ )
+ assertions.append(assertion)
+ failures = [assertion for assertion in assertions if not assertion.passed]
+ if any(item.severity == "hard" for item in failures):
+ score, level = 0.0, "fail"
+ elif any(item.severity == "major" for item in failures):
+ score, level = 0.6, "pass"
+ elif failures:
+ score, level = 0.8, "good"
+ else:
+ score, level = 1.0, "excellent"
+ reason = (
+ "All compliance rules passed."
+ if not failures
+ else f"{len(failures)} compliance rule(s) failed."
+ )
+ return self.result(case, score, level, reason)
+
+ def new_accumulator(self, window: Window | None = None) -> MetricAccumulator:
+ return ComplianceAccumulator(self.metric, window)
+
+
+class ComplianceAccumulator(MetricAccumulator):
+ """Keep one static compliance result for each fingerprint version."""
+
+ def _aggregate_group(self, results: list[MetricResult]) -> MetricResult:
+ applicable = [result for result in results if result.score is not None]
+ if not applicable:
+ return super()._aggregate_group(results)
+ result = applicable[0]
+ metrics = dict(result.metrics)
+ metrics["result_count"] = 1
+ return MetricResult(
+ metric=result.metric,
+ type=result.type,
+ id=result.id,
+ version=result.version,
+ event_time=None,
+ score=result.score,
+ level=result.level,
+ reason="",
+ metrics=metrics,
+ )
diff --git a/jiuwenswarm/symphony/evaluation/evaluators/latency.py b/jiuwenswarm/symphony/evaluation/evaluators/latency.py
new file mode 100644
index 0000000000..aa0f946a4e
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/evaluators/latency.py
@@ -0,0 +1,280 @@
+"""Latency scenario classification, evaluation, and aggregation."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, replace
+from typing import Any, Literal, TypeAlias
+
+from json_repair import repair_json
+
+from jiuwenswarm.symphony.evaluation.aggregation import MetricAccumulator
+from jiuwenswarm.symphony.evaluation.evaluators.base import BaseEvaluator
+from jiuwenswarm.symphony.evaluation.interfaces import EvaluationLLM
+from jiuwenswarm.symphony.evaluation.models import (
+ EvaluationCase,
+ MetricLevel,
+ MetricResult,
+ Window,
+)
+from jiuwenswarm.symphony.fingerprint.models import Fingerprint
+
+
+LatencyScenario: TypeAlias = Literal[
+ "realtime_interaction",
+ "short_task",
+ "long",
+]
+LATENCY_SCENARIOS = {
+ "realtime_interaction",
+ "short_task",
+ "long",
+}
+
+
+@dataclass(frozen=True)
+class LatencyScenarioResult:
+ """Latency scenario inferred once from one static fingerprint."""
+
+ scenario: LatencyScenario
+ reason: str
+
+
+class LatencyScenarioClassifier:
+ """Use an LLM to classify latency expectations from static data."""
+
+ def __init__(self, llm: EvaluationLLM) -> None:
+ self.llm = llm
+
+ def classify(self, fingerprint: Fingerprint) -> LatencyScenarioResult:
+ response = self.llm.chat(
+ [{"role": "user", "content": self._prompt(fingerprint)}]
+ )
+ payload = self._parse(response)
+ scenario = payload.get("scenario")
+ reason = payload.get("reason")
+ if scenario not in LATENCY_SCENARIOS:
+ raise ValueError("Model returned an unsupported latency scenario.")
+ if not isinstance(reason, str) or not reason.strip():
+ raise ValueError("Model response must contain a latency scenario reason.")
+ return LatencyScenarioResult(scenario=scenario, reason=reason.strip())
+
+ def apply(self, fingerprint: Fingerprint) -> Fingerprint:
+ """Return a fingerprint enriched with its static scenario result."""
+
+ result = self.classify(fingerprint)
+ static_data = dict(fingerprint.static_data)
+ evaluation_data = static_data.get("evaluation", {})
+ evaluation_data = (
+ dict(evaluation_data) if isinstance(evaluation_data, dict) else {}
+ )
+ evaluation_data.update(
+ {
+ "latency_scenario": result.scenario,
+ "latency_scenario_reason": result.reason,
+ }
+ )
+ static_data["evaluation"] = evaluation_data
+ return replace(fingerprint, static_data=static_data)
+
+ @staticmethod
+ def _parse(response: list[str]) -> dict[str, Any]:
+ if not response or not isinstance(response[0], str):
+ raise ValueError("Model returned no latency scenario response.")
+ payload = repair_json(response[0], return_objects=True)
+ if not isinstance(payload, dict):
+ raise ValueError("Latency scenario response must be a JSON object.")
+ return payload
+
+ @staticmethod
+ def _prompt(fingerprint: Fingerprint) -> str:
+ static_payload = {
+ "type": fingerprint.type,
+ "name": fingerprint.name,
+ "description": fingerprint.description,
+ }
+ return (
+ "Classify the latency scenario for this Agent or Skill from static data.\n"
+ "Choose exactly one scenario:\n"
+ "- realtime_interaction: Q&A or interactive calls requiring an immediate "
+ "first response.\n"
+ "- short_task: creation or productivity work expected to finish within "
+ "a short period.\n"
+ "- long: asynchronous research, document, audio, or video work with long "
+ "execution time.\n"
+ "Return only JSON with scenario and reason.\n"
+ f"Static data:\n{json.dumps(static_payload, ensure_ascii=False, default=str)}"
+ )
+
+
+class LatencyEvaluator(BaseEvaluator):
+ metric = "latency"
+
+ def __init__(
+ self,
+ scenario: LatencyScenario | None = "short_task",
+ thresholds_ms: tuple[float, float, float] | None = None,
+ ) -> None:
+ if scenario is not None and scenario not in LATENCY_SCENARIOS:
+ raise ValueError(f"Unsupported latency scenario: {scenario}")
+ if scenario is None and thresholds_ms is not None:
+ raise ValueError(
+ "Custom latency thresholds require one fixed latency scenario."
+ )
+ self.scenario = scenario
+ self.thresholds_ms = thresholds_ms
+ configured_thresholds = thresholds_ms or (
+ self._default_thresholds(scenario) if scenario is not None else None
+ )
+ if configured_thresholds is not None and any(
+ value < 0 for value in configured_thresholds
+ ):
+ raise ValueError("Latency thresholds must be non-negative.")
+ if configured_thresholds is not None and (
+ tuple(sorted(configured_thresholds)) != configured_thresholds
+ ):
+ raise ValueError("Latency thresholds must be ascending.")
+
+ @staticmethod
+ def _default_thresholds(
+ scenario: LatencyScenario,
+ ) -> tuple[float, float, float]:
+ if scenario == "realtime_interaction":
+ return (5_000.0, 10_000.0, 15_000.0)
+ return (30_000.0, 60_000.0, 90_000.0)
+
+ def _scenario(self, case: EvaluationCase) -> LatencyScenario | None:
+ if self.scenario is not None:
+ return self.scenario
+ evaluation_data = case.fingerprint.static_data.get("evaluation", {})
+ if not isinstance(evaluation_data, dict):
+ return None
+ scenario = evaluation_data.get("latency_scenario")
+ return scenario if scenario in LATENCY_SCENARIOS else None
+
+ def _value(
+ self,
+ case: EvaluationCase,
+ scenario: LatencyScenario,
+ ) -> float | None:
+ if case.latency is None:
+ return None
+ if scenario == "realtime_interaction":
+ return case.latency.ttft
+ return case.latency.e2e
+
+ def level_for(self, value: float, scenario: LatencyScenario) -> MetricLevel:
+ if scenario == "long":
+ return "excellent"
+ thresholds = self.thresholds_ms or self._default_thresholds(scenario)
+ excellent, good, passing = thresholds
+ if value <= excellent:
+ return "excellent"
+ if value <= good:
+ return "good"
+ if value <= passing:
+ return "pass"
+ return "fail"
+
+ def evaluate(self, case: EvaluationCase) -> MetricResult:
+ scenario = self._scenario(case)
+ if scenario is None:
+ return self.not_applicable(
+ case,
+ "The fingerprint has no classified latency scenario.",
+ )
+ value = self._value(case, scenario)
+ if value is None:
+ return self.not_applicable(case, "Required latency data is missing.")
+ level = self.level_for(value, scenario)
+ score = {"excellent": 1.0, "good": 0.8, "pass": 0.6, "fail": 0.0}[level]
+ latency = case.latency
+ if latency is None:
+ return self.not_applicable(case, "Required latency data is missing.")
+ return self.result(
+ case,
+ score,
+ level,
+ f"{scenario} latency is {value:g} ms.",
+ metrics={
+ "scenario": scenario,
+ "ttft": latency.ttft,
+ "e2e": latency.e2e,
+ },
+ )
+
+ def new_accumulator(self, window: Window | None = None) -> MetricAccumulator:
+ return LatencyAccumulator(self, window)
+
+
+def _percentile(values: list[float], percentile: float) -> float:
+ ordered = sorted(values)
+ if len(ordered) == 1:
+ return ordered[0]
+ position = (len(ordered) - 1) * percentile
+ lower = int(position)
+ upper = min(lower + 1, len(ordered) - 1)
+ fraction = position - lower
+ return ordered[lower] + (ordered[upper] - ordered[lower]) * fraction
+
+
+class LatencyAccumulator(MetricAccumulator):
+ """Aggregate latency distributions while grading the scenario p95."""
+
+ def __init__(self, evaluator: LatencyEvaluator, window: Window | None) -> None:
+ super().__init__(
+ evaluator.metric,
+ window,
+ aggregation_thresholds=evaluator.aggregation_thresholds,
+ )
+ self.evaluator = evaluator
+
+ def _aggregate_group(self, results: list[MetricResult]) -> MetricResult:
+ applicable = [result for result in results if result.score is not None]
+ template = results[0]
+ if not applicable:
+ return super()._aggregate_group(results)
+
+ def distribution(name: str) -> dict[str, float] | None:
+ values = [
+ float(result.metrics[name])
+ for result in applicable
+ if result.metrics.get(name) is not None
+ ]
+ if not values:
+ return None
+ return {
+ "avg": sum(values) / len(values),
+ "p95": _percentile(values, 0.95),
+ "p99": _percentile(values, 0.99),
+ }
+
+ ttft = distribution("ttft")
+ e2e = distribution("e2e")
+ scenarios = {result.metrics.get("scenario") for result in applicable}
+ if len(scenarios) != 1:
+ raise ValueError("One fingerprint version has multiple latency scenarios.")
+ scenario = scenarios.pop()
+ if scenario not in LATENCY_SCENARIOS:
+ raise ValueError("Latency result has an unsupported scenario.")
+ selected = ttft if scenario == "realtime_interaction" else e2e
+ if selected is None:
+ raise ValueError("Latency results are missing the required distribution.")
+ level = self.evaluator.level_for(selected["p95"], scenario)
+ score = {"excellent": 1.0, "good": 0.8, "pass": 0.6, "fail": 0.0}[level]
+ return MetricResult(
+ metric=self.metric,
+ type=template.type,
+ id=template.id,
+ version=template.version,
+ event_time=None,
+ score=score,
+ level=level,
+ reason="",
+ metrics={
+ "scenario": scenario,
+ "result_count": len(applicable),
+ "ttft": ttft,
+ "e2e": e2e,
+ },
+ )
diff --git a/jiuwenswarm/symphony/evaluation/evaluators/success_rate.py b/jiuwenswarm/symphony/evaluation/evaluators/success_rate.py
new file mode 100644
index 0000000000..92d970783d
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/evaluators/success_rate.py
@@ -0,0 +1,20 @@
+"""Execution success-rate evaluator."""
+
+from jiuwenswarm.symphony.evaluation.evaluators.base import BaseEvaluator
+from jiuwenswarm.symphony.evaluation.models import (
+ EvaluationCase,
+ MetricLevel,
+ MetricResult,
+)
+
+
+class SuccessRateEvaluator(BaseEvaluator):
+ metric = "success_rate"
+
+ def evaluate(self, case: EvaluationCase) -> MetricResult:
+ if case.success is None:
+ return self.not_applicable(case, "The execution success flag is missing.")
+ score = 1.0 if case.success else 0.0
+ level: MetricLevel = "excellent" if case.success else "fail"
+ reason = "Execution succeeded." if case.success else "Execution failed."
+ return self.result(case, score, level, reason)
diff --git a/jiuwenswarm/symphony/evaluation/interfaces.py b/jiuwenswarm/symphony/evaluation/interfaces.py
new file mode 100644
index 0000000000..70c201df0d
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/interfaces.py
@@ -0,0 +1,18 @@
+"""Protocols for evaluation module integrations."""
+
+from typing import Any, Dict, List, Protocol, Sequence, Union
+
+
+PromptInput = Union[str, Sequence[str]]
+Message = Dict[str, str]
+MessageInput = Union[Sequence[Message], Sequence[Sequence[Message]]]
+
+
+class EvaluationLLM(Protocol):
+ """Minimal model interface required by Symphony evaluation."""
+
+ def generate(self, prompts: PromptInput, **kwargs: Any) -> List[str]:
+ """Generate text for one or more prompts."""
+
+ def chat(self, messages: MessageInput, **kwargs: Any) -> List[str]:
+ """Generate text for one or more chat conversations."""
diff --git a/jiuwenswarm/symphony/evaluation/models.py b/jiuwenswarm/symphony/evaluation/models.py
new file mode 100644
index 0000000000..8067f5b031
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/models.py
@@ -0,0 +1,192 @@
+# -*- coding: utf-8 -*-
+"""Public data contracts for Agent and Skill evaluation."""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field
+from datetime import date, datetime
+from typing import Any, Literal, TypeAlias
+
+from openai.types.chat import ChatCompletionMessageParam
+
+from jiuwenswarm.symphony.fingerprint.models import Fingerprint
+
+
+MetricLevel: TypeAlias = Literal["excellent", "good", "pass", "fail", "not_applicable"]
+Confidence: TypeAlias = Literal["none", "low", "normal"]
+ComplianceSeverity: TypeAlias = Literal["light", "major", "hard"]
+
+
+def to_json_safe(value: Any) -> Any:
+ """Recursively convert supported values to strict JSON-compatible data."""
+
+ if value is None or isinstance(value, (str, bool, int)):
+ return value
+ if isinstance(value, float):
+ if not math.isfinite(value):
+ raise ValueError("JSON numbers must be finite.")
+ return value
+ if isinstance(value, datetime):
+ return value.isoformat()
+ if isinstance(value, date):
+ return value.isoformat()
+ if isinstance(value, list):
+ return [to_json_safe(item) for item in value]
+ if isinstance(value, dict):
+ converted: dict[str, Any] = {}
+ for key, item in value.items():
+ if not isinstance(key, str):
+ raise TypeError("JSON object keys must be strings.")
+ converted[key] = to_json_safe(item)
+ return converted
+ raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable.")
+
+
+@dataclass(frozen=True)
+class Latency:
+ """Execution latency summary; TTFT and E2E values use milliseconds."""
+
+ ttft: float | None = None
+ e2e: float | None = None
+
+ def __post_init__(self) -> None:
+ for name, value in (
+ ("ttft", self.ttft),
+ ("e2e", self.e2e),
+ ):
+ if value is not None and (not math.isfinite(value) or value < 0):
+ raise ValueError(f"Latency {name} must be finite and non-negative.")
+
+
+@dataclass(frozen=True)
+class EvaluationCase:
+ """A complete execution sample and the evaluated static fingerprint."""
+
+ fingerprint: Fingerprint
+ message: list[ChatCompletionMessageParam] = field(default_factory=list)
+ success: bool | None = None
+ latency: Latency | None = None
+ event_time: datetime | None = None
+
+ @property
+ def input_contents(self) -> list[Any]:
+ return [
+ item.get("content")
+ for item in self.message
+ if item.get("role") == "user" and item.get("content") is not None
+ ]
+
+ @property
+ def final_output(self) -> Any | None:
+ for item in reversed(self.message):
+ if item.get("role") == "assistant":
+ return item.get("content")
+ return None
+
+
+@dataclass(frozen=True)
+class AssertionResult:
+ """A deterministic assertion produced by a compliance rule."""
+
+ code: str
+ passed: bool
+ severity: ComplianceSeverity = "hard"
+ reason: str = ""
+ evidence: list[dict[str, Any]] = field(default_factory=list)
+
+ def __post_init__(self) -> None:
+ if self.severity not in {"light", "major", "hard"}:
+ raise ValueError(
+ "AssertionResult severity must be 'light', 'major', or 'hard'."
+ )
+
+ def to_dict(self) -> dict[str, Any]:
+ return to_json_safe(
+ {
+ "code": self.code,
+ "passed": self.passed,
+ "severity": self.severity,
+ "reason": self.reason,
+ "evidence": self.evidence,
+ }
+ )
+
+
+@dataclass(frozen=True)
+class MetricResult:
+ """Result returned by one independently deployable metric evaluator."""
+
+ metric: str
+ type: str
+ id: str
+ version: str
+ event_time: datetime | None
+ score: float | None
+ level: MetricLevel
+ reason: str
+ metrics: dict[str, Any] = field(default_factory=dict)
+
+ def __post_init__(self) -> None:
+ if self.score is not None and not 0 <= self.score <= 1:
+ raise ValueError("MetricResult score must be between 0 and 1.")
+ if self.score is None and self.level != "not_applicable":
+ raise ValueError("A missing score must use level 'not_applicable'.")
+
+ def to_dict(self) -> dict[str, Any]:
+ return to_json_safe(
+ {
+ "metric": self.metric,
+ "type": self.type,
+ "id": self.id,
+ "version": self.version,
+ "event_time": self.event_time,
+ "score": self.score,
+ "level": self.level,
+ "reason": self.reason,
+ "metrics": self.metrics,
+ }
+ )
+
+
+@dataclass(frozen=True)
+class Window:
+ """Optional aggregation window metadata controlled by the caller."""
+
+ start: datetime | None = None
+ end: datetime | None = None
+ label: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return to_json_safe({"start": self.start, "end": self.end, "label": self.label})
+
+
+@dataclass(frozen=True)
+class QualityResult:
+ """Per-object window aggregation without an object-level quality score."""
+
+ type: str
+ id: str
+ version: str
+ window: Window | None
+ result_count: int
+ metrics: dict[str, MetricResult]
+ confidence: Confidence
+
+ def to_dict(self) -> dict[str, Any]:
+ metrics = {}
+ for name, result in self.metrics.items():
+ payload = result.to_dict()
+ payload.pop("reason", None)
+ metrics[name] = payload
+ return to_json_safe(
+ {
+ "type": self.type,
+ "id": self.id,
+ "version": self.version,
+ "window": self.window.to_dict() if self.window else None,
+ "result_count": self.result_count,
+ "metrics": metrics,
+ "confidence": self.confidence,
+ }
+ )
diff --git a/jiuwenswarm/symphony/evaluation/suite.py b/jiuwenswarm/symphony/evaluation/suite.py
new file mode 100644
index 0000000000..8e496f4463
--- /dev/null
+++ b/jiuwenswarm/symphony/evaluation/suite.py
@@ -0,0 +1,145 @@
+# -*- coding: utf-8 -*-
+"""Multi-metric orchestration and per-object aggregation."""
+
+from __future__ import annotations
+
+from typing import Iterable
+
+from jiuwenswarm.symphony.evaluation.evaluators import (
+ AccuracyEvaluator,
+ BaseEvaluator,
+ CompletenessEvaluator,
+ ComplianceEvaluator,
+ LatencyEvaluator,
+ SuccessRateEvaluator,
+)
+from jiuwenswarm.symphony.evaluation.models import (
+ Confidence,
+ EvaluationCase,
+ MetricResult,
+ QualityResult,
+ Window,
+)
+
+
+class EvaluationAccumulator:
+ """Aggregate Suite results into one QualityResult per object identity."""
+
+ def __init__(
+ self,
+ evaluators: Iterable[BaseEvaluator],
+ window: Window | None = None,
+ ) -> None:
+ self.window = window
+ self._accumulators = {
+ evaluator.metric: evaluator.new_accumulator(window)
+ for evaluator in evaluators
+ }
+ self._identities: set[tuple[str, str, str]] = set()
+ self._required_metrics = frozenset(self._accumulators)
+
+ def add(self, results: dict[str, MetricResult]) -> "EvaluationAccumulator":
+ if frozenset(results) != self._required_metrics:
+ raise ValueError(
+ "Evaluation results must contain all five metrics exactly once."
+ )
+ identities = {
+ (result.type, result.id, result.version) for result in results.values()
+ }
+ if len(identities) != 1:
+ raise ValueError("Evaluation results must share one fingerprint identity.")
+ if any(result.metric != metric for metric, result in results.items()):
+ raise ValueError("Each result must match its metric mapping key.")
+ for metric, result in results.items():
+ self._accumulators[metric].add(result)
+ self._identities.update(identities)
+ return self
+
+ def extend(
+ self, batches: Iterable[dict[str, MetricResult]]
+ ) -> "EvaluationAccumulator":
+ for results in batches:
+ self.add(results)
+ return self
+
+ def aggregate(self) -> list[QualityResult]:
+ by_metric: dict[str, dict[tuple[str, str, str], MetricResult]] = {}
+ for metric, accumulator in self._accumulators.items():
+ by_metric[metric] = {
+ (result.type, result.id, result.version): result
+ for result in accumulator.aggregate()
+ }
+ quality_results: list[QualityResult] = []
+ for identity in sorted(self._identities):
+ metrics = {
+ metric: grouped[identity]
+ for metric, grouped in by_metric.items()
+ if identity in grouped
+ }
+ counts = [
+ int(result.metrics.get("result_count", 0))
+ for result in metrics.values()
+ ]
+ result_count = max(counts, default=0)
+ confidence: Confidence
+ if result_count == 0:
+ confidence = "none"
+ elif result_count == 1:
+ confidence = "low"
+ else:
+ confidence = "normal"
+ quality_results.append(
+ QualityResult(
+ type=identity[0],
+ id=identity[1],
+ version=identity[2],
+ window=self.window,
+ result_count=result_count,
+ metrics=metrics,
+ confidence=confidence,
+ )
+ )
+ return quality_results
+
+
+class EvaluationSuite:
+ """Evaluate the fixed five-dimensional quality model."""
+
+ def __init__(self, evaluators: Iterable[BaseEvaluator] | None = None) -> None:
+ selected = (
+ list(evaluators)
+ if evaluators is not None
+ else [
+ SuccessRateEvaluator(),
+ LatencyEvaluator(),
+ AccuracyEvaluator(),
+ CompletenessEvaluator(),
+ ComplianceEvaluator(),
+ ]
+ )
+ metrics = [evaluator.metric for evaluator in selected]
+ required_metrics = {
+ "success_rate",
+ "latency",
+ "accuracy",
+ "completeness",
+ "compliance",
+ }
+ if len(metrics) != len(set(metrics)) or set(metrics) != required_metrics:
+ raise ValueError(
+ "EvaluationSuite requires exactly the five standard metrics."
+ )
+ self.evaluators = selected
+
+ def evaluate(self, case: EvaluationCase) -> dict[str, MetricResult]:
+ return {
+ evaluator.metric: evaluator.evaluate(case) for evaluator in self.evaluators
+ }
+
+ def evaluate_batch(
+ self, cases: Iterable[EvaluationCase]
+ ) -> list[dict[str, MetricResult]]:
+ return [self.evaluate(case) for case in cases]
+
+ def new_accumulator(self, window: Window | None = None) -> EvaluationAccumulator:
+ return EvaluationAccumulator(self.evaluators, window)
diff --git a/jiuwenswarm/symphony/fingerprint/__init__.py b/jiuwenswarm/symphony/fingerprint/__init__.py
index ba4eb66e2c..7e53a1077c 100644
--- a/jiuwenswarm/symphony/fingerprint/__init__.py
+++ b/jiuwenswarm/symphony/fingerprint/__init__.py
@@ -22,8 +22,9 @@ from jiuwenswarm.symphony.fingerprint.models import (
ParameterSpec,
RawSkillManifest,
FingerprintExtractionResult,
+ Fingerprint,
+ FingerprintType,
SkillFolder,
- SkillFingerprint,
SkillSchemaExtractor,
)
@@ -84,8 +85,9 @@ __all__ = [
"ParameterSpec",
"RawSkillManifest",
"FingerprintExtractionResult",
+ "Fingerprint",
+ "FingerprintType",
"SkillFolder",
- "SkillFingerprint",
"SkillSchemaExtractor",
# Stage: scan
"SkillFolderScanner",
diff --git a/jiuwenswarm/symphony/fingerprint/incremental.py b/jiuwenswarm/symphony/fingerprint/incremental.py
index a4cc496b39..5bc7204b07 100644
--- a/jiuwenswarm/symphony/fingerprint/incremental.py
+++ b/jiuwenswarm/symphony/fingerprint/incremental.py
@@ -12,10 +12,10 @@ from typing import Any, Callable
from jiuwenswarm.symphony.fingerprint.models import (
ExtractionDiagnostic,
+ Fingerprint,
NormalizationDecision,
NormalizationResult,
SkillFolder,
- SkillFingerprint,
)
from jiuwenswarm.symphony.fingerprint.normalize import (
IONameVocabulary,
@@ -30,8 +30,8 @@ IndexedSkillFolder = tuple[int, SkillFolder]
@dataclass(frozen=True)
class FingerprintReusePlan:
changed_folders: list[IndexedSkillFolder]
- fingerprints: list[SkillFingerprint]
- fingerprints_by_path: dict[str, SkillFingerprint]
+ fingerprints: list[Fingerprint]
+ fingerprints_by_path: dict[str, Fingerprint]
removed_paths: set[str]
reused_count: int
@@ -53,7 +53,7 @@ class IncrementalFingerprintStore:
current_hashes: dict[str, str],
*,
force: bool,
- on_reuse: Callable[[int, SkillFolder, SkillFingerprint], None] | None = None,
+ on_reuse: Callable[[int, SkillFolder, Fingerprint], None] | None = None,
) -> FingerprintReusePlan:
old_active_entries = self.old_state.active_entries()
removed_paths = {
@@ -62,8 +62,8 @@ class IncrementalFingerprintStore:
if relative_path not in current_hashes
}
changed_folders: list[IndexedSkillFolder] = []
- fingerprints: list[SkillFingerprint] = []
- fingerprints_by_path: dict[str, SkillFingerprint] = {}
+ fingerprints: list[Fingerprint] = []
+ fingerprints_by_path: dict[str, Fingerprint] = {}
reused_count = 0
for folder_index, folder in enumerate(folders):
@@ -144,7 +144,7 @@ class FingerprintResultCache:
if not isinstance(fingerprint_payload, dict):
return None
return NormalizationResult(
- fingerprint=SkillFingerprint.from_dict(fingerprint_payload),
+ fingerprint=Fingerprint.from_dict(fingerprint_payload),
diagnostics=[
_diagnostic_from_dict(item)
for item in payload.get("diagnostics", [])
@@ -187,13 +187,13 @@ class FingerprintResultCache:
return self.root / f"{digest}.json"
-def load_fingerprints(output_dir: Path) -> list[SkillFingerprint]:
+def load_fingerprints(output_dir: Path) -> list[Fingerprint]:
path = resolve_score_artifact_dir(output_dir) / "fingerprints.json"
if not path.exists():
return []
payload = json.loads(path.read_text(encoding="utf-8"))
return [
- SkillFingerprint.from_dict(item)
+ Fingerprint.from_dict(item)
for item in payload.get("fingerprints", [])
if isinstance(item, dict)
]
diff --git a/jiuwenswarm/symphony/fingerprint/models.py b/jiuwenswarm/symphony/fingerprint/models.py
index b92e03ffc8..68311b03c4 100644
--- a/jiuwenswarm/symphony/fingerprint/models.py
+++ b/jiuwenswarm/symphony/fingerprint/models.py
@@ -3,9 +3,22 @@
from __future__ import annotations
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field as dataclass_field
from pathlib import Path
-from typing import Any, Dict, List, Optional, Protocol, Union
+from typing import (
+ Any,
+ Dict,
+ List,
+ Literal,
+ Optional,
+ Protocol,
+ TypeAlias,
+ Union,
+ cast,
+)
+
+
+FingerprintType: TypeAlias = Literal["agent", "skill"]
@dataclass(frozen=True)
@@ -28,7 +41,7 @@ class ExtractionDiagnostic:
message: str
skill_id: Optional[str] = None
path: Optional[str] = None
- details: Dict[str, Any] = field(default_factory=dict)
+ details: Dict[str, Any] = dataclass_field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
return {
@@ -50,7 +63,7 @@ class RawSkillManifest:
frontmatter: Dict[str, Any]
body: str
body_sha256: str
- diagnostics: List[ExtractionDiagnostic] = field(default_factory=list)
+ diagnostics: List[ExtractionDiagnostic] = dataclass_field(default_factory=list)
@dataclass(frozen=True)
@@ -94,25 +107,63 @@ class ExtractedSkillSchema:
"""LLM-extracted candidate schema before deterministic normalization."""
description: str = ""
- inputs: List[Union[ParameterSpec, Dict[str, Any]]] = field(default_factory=list)
- outputs: List[Union[ArtifactSpec, Dict[str, Any]]] = field(default_factory=list)
+ inputs: List[Union[ParameterSpec, Dict[str, Any]]] = dataclass_field(
+ default_factory=list
+ )
+ outputs: List[Union[ArtifactSpec, Dict[str, Any]]] = dataclass_field(
+ default_factory=list
+ )
confidence: Optional[float] = None
- warnings: List[str] = field(default_factory=list)
+ warnings: List[str] = dataclass_field(default_factory=list)
@dataclass(frozen=True)
-class SkillFingerprint:
- """Normalized Skill fingerprint v1."""
+class Fingerprint:
+ """Normalized static description of an Agent or Skill."""
+ type: FingerprintType
id: str
name: str
description: str
version: str
- inputs: List[ParameterSpec]
- outputs: List[ArtifactSpec]
+ inputs: List[ParameterSpec] = dataclass_field(default_factory=list)
+ outputs: List[ArtifactSpec] = dataclass_field(default_factory=list)
+ static_data: Dict[str, Any] = dataclass_field(default_factory=dict)
+
+ def __post_init__(self) -> None:
+ if self.type not in {"agent", "skill"}:
+ raise ValueError("Fingerprint type must be 'agent' or 'skill'.")
+ for name, value in (
+ ("id", self.id),
+ ("name", self.name),
+ ("version", self.version),
+ ):
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError(f"Fingerprint {name} must be a non-empty string.")
+ if any(not isinstance(item, ParameterSpec) for item in self.inputs):
+ raise ValueError("Fingerprint inputs must contain ParameterSpec objects.")
+ if any(not isinstance(item, ArtifactSpec) for item in self.outputs):
+ raise ValueError("Fingerprint outputs must contain ArtifactSpec objects.")
+ if not isinstance(self.static_data, dict):
+ raise ValueError("Fingerprint static_data must be a dictionary.")
def to_dict(self) -> Dict[str, Any]:
return {
+ "type": self.type,
+ "id": self.id,
+ "name": self.name,
+ "description": self.description,
+ "version": self.version,
+ "inputs": [item.to_dict() for item in self.inputs],
+ "outputs": [item.to_dict() for item in self.outputs],
+ "static_data": self.static_data,
+ }
+
+ def graph_identity_dict(self) -> Dict[str, Any]:
+ """Return fields that define graph identity and matching behavior."""
+
+ return {
+ "type": self.type,
"id": self.id,
"name": self.name,
"description": self.description,
@@ -122,12 +173,32 @@ class SkillFingerprint:
}
@classmethod
- def from_dict(cls, payload: Dict[str, Any]) -> "SkillFingerprint":
+ def from_dict(cls, payload: Dict[str, Any]) -> "Fingerprint":
+ if not isinstance(payload, dict):
+ raise ValueError("Fingerprint payload must be a dictionary.")
+ raw_type = str(payload.get("type") or "")
+ if raw_type not in {"agent", "skill"}:
+ raise ValueError("Fingerprint type must be 'agent' or 'skill'.")
+ raw_inputs = payload.get("inputs", [])
+ raw_outputs = payload.get("outputs", [])
+ raw_static_data = payload.get("static_data", {})
+ if not isinstance(raw_inputs, list):
+ raise ValueError("Fingerprint inputs must be a list.")
+ if any(not isinstance(item, dict) for item in raw_inputs):
+ raise ValueError("Fingerprint inputs must contain dictionaries.")
+ if not isinstance(raw_outputs, list):
+ raise ValueError("Fingerprint outputs must be a list.")
+ if any(not isinstance(item, dict) for item in raw_outputs):
+ raise ValueError("Fingerprint outputs must contain dictionaries.")
+ if not isinstance(raw_static_data, dict):
+ raise ValueError("Fingerprint static_data must be a dictionary.")
+ fingerprint_type = cast(FingerprintType, raw_type)
return cls(
- id=str(payload.get("id") or ""),
- name=str(payload.get("name") or ""),
+ type=fingerprint_type,
+ id=payload.get("id", ""),
+ name=payload.get("name", ""),
description=str(payload.get("description") or ""),
- version=str(payload.get("version") or "1.0.0"),
+ version=payload.get("version", "1.0.0"),
inputs=[
ParameterSpec(
name=str(item.get("name") or "input"),
@@ -136,7 +207,7 @@ class SkillFingerprint:
description=str(item.get("description") or ""),
default=item.get("default"),
)
- for item in payload.get("inputs", [])
+ for item in raw_inputs
],
outputs=[
ArtifactSpec(
@@ -144,8 +215,9 @@ class SkillFingerprint:
type=str(item.get("type") or "unknown"),
description=str(item.get("description") or ""),
)
- for item in payload.get("outputs", [])
+ for item in raw_outputs
],
+ static_data=dict(raw_static_data),
)
@@ -154,7 +226,7 @@ class NormalizationConfig:
"""Configuration and vocabularies used by the deterministic normalizer.
This object owns the normalizer defaults, vocabulary versions, and optional
- alias maps. `SkillFingerprint` keeps only normalized `name` and `type`
+ alias maps. `Fingerprint` keeps only normalized `name` and `type`
values; the evidence for each choice is stored in `NormalizationDecision`.
`name` and `type` have different roles:
@@ -218,7 +290,7 @@ class NormalizationDecision:
vocab: str
vocab_version: str
confidence: float
- details: Dict[str, Any] = field(default_factory=dict)
+ details: Dict[str, Any] = dataclass_field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
return {
@@ -239,22 +311,26 @@ class NormalizationDecision:
@dataclass(frozen=True)
class NormalizationResult:
- fingerprint: SkillFingerprint
+ fingerprint: Fingerprint
diagnostics: List[ExtractionDiagnostic]
- decisions: List[NormalizationDecision] = field(default_factory=list)
+ decisions: List[NormalizationDecision] = dataclass_field(default_factory=list)
@dataclass(frozen=True)
class FingerprintExtractionResult:
- fingerprints: List[SkillFingerprint]
+ fingerprints: List[Fingerprint]
diagnostics: List[ExtractionDiagnostic]
- normalization_decisions: List[NormalizationDecision] = field(default_factory=list)
- io_name_vocab: Dict[str, Any] = field(default_factory=dict)
- llm_token_usage: Dict[str, Any] = field(default_factory=dict)
- folders: List[SkillFolder] = field(default_factory=list)
- current_hashes: Dict[str, str] = field(default_factory=dict)
- removed_paths: set[str] = field(default_factory=set)
- fingerprints_by_path: Dict[str, SkillFingerprint] = field(default_factory=dict)
+ normalization_decisions: List[NormalizationDecision] = dataclass_field(
+ default_factory=list
+ )
+ io_name_vocab: Dict[str, Any] = dataclass_field(default_factory=dict)
+ llm_token_usage: Dict[str, Any] = dataclass_field(default_factory=dict)
+ folders: List[SkillFolder] = dataclass_field(default_factory=list)
+ current_hashes: Dict[str, str] = dataclass_field(default_factory=dict)
+ removed_paths: set[str] = dataclass_field(default_factory=set)
+ fingerprints_by_path: Dict[str, Fingerprint] = dataclass_field(
+ default_factory=dict
+ )
reused_count: int = 0
extracted_count: int = 0
diff --git a/jiuwenswarm/symphony/fingerprint/normalize/data_types.py b/jiuwenswarm/symphony/fingerprint/normalize/data_types.py
index f9fd0362a3..4b5830f203 100644
--- a/jiuwenswarm/symphony/fingerprint/normalize/data_types.py
+++ b/jiuwenswarm/symphony/fingerprint/normalize/data_types.py
@@ -10,7 +10,7 @@ from jiuwenswarm.symphony.fingerprint.models import (
NormalizationConfig,
NormalizationDecision,
RawSkillManifest,
- SkillFingerprint,
+ Fingerprint,
)
from jiuwenswarm.symphony.fingerprint.normalize.data_type_vocab import (
DataTypeInference,
@@ -260,7 +260,7 @@ class DataTypeNormalizer:
def validate(
self,
- fingerprint: SkillFingerprint,
+ fingerprint: Fingerprint,
manifest: RawSkillManifest,
diagnostics: List[ExtractionDiagnostic],
) -> None:
diff --git a/jiuwenswarm/symphony/fingerprint/normalize/normalizer.py b/jiuwenswarm/symphony/fingerprint/normalize/normalizer.py
index 7e941bb106..07f98e00fd 100644
--- a/jiuwenswarm/symphony/fingerprint/normalize/normalizer.py
+++ b/jiuwenswarm/symphony/fingerprint/normalize/normalizer.py
@@ -12,7 +12,7 @@ from jiuwenswarm.symphony.fingerprint.models import (
NormalizationDecision,
NormalizationResult,
RawSkillManifest,
- SkillFingerprint,
+ Fingerprint,
)
from jiuwenswarm.symphony.fingerprint.normalize.data_type_vocab import DataTypeVocabulary
from jiuwenswarm.symphony.fingerprint.normalize.data_types import DataTypeNormalizer
@@ -47,7 +47,7 @@ class _NormalizationContext:
class SkillFingerprintNormalizer:
- """Convert ExtractedSkillSchema batches into SkillFingerprint v1."""
+ """Convert extracted Skill schemas into unified fingerprints."""
def __init__(
self,
@@ -166,7 +166,8 @@ class SkillFingerprintNormalizer:
context.decisions,
)
- fingerprint = SkillFingerprint(
+ fingerprint = Fingerprint(
+ type="skill",
id=context.skill_id,
name=context.name,
description=context.description,
diff --git a/jiuwenswarm/symphony/graph/candidates/generator.py b/jiuwenswarm/symphony/graph/candidates/generator.py
index 85c6aad212..0f8406e67f 100644
--- a/jiuwenswarm/symphony/graph/candidates/generator.py
+++ b/jiuwenswarm/symphony/graph/candidates/generator.py
@@ -9,7 +9,7 @@ from typing import Dict, Iterable, List, MutableMapping, Set, Tuple
from jiuwenswarm.symphony.fingerprint.models import (
ArtifactSpec,
ParameterSpec,
- SkillFingerprint,
+ Fingerprint,
)
from jiuwenswarm.symphony.fingerprint.normalize.data_type_vocab import (
DataTypeVocabulary,
@@ -186,7 +186,7 @@ class CandidateGenerator:
def _add_semantic_overlap_candidates(
self,
- skills: List[SkillFingerprint],
+ skills: List[Fingerprint],
skill_terms: Dict[str, Set[str]],
candidates: MutableMapping[Tuple[str, str], RelationCandidate],
) -> None:
@@ -245,7 +245,7 @@ class CandidateGenerator:
def _add_textual_coercion_candidates(
self,
- skills: List[SkillFingerprint],
+ skills: List[Fingerprint],
skill_terms: Dict[str, Set[str]],
candidates: MutableMapping[Tuple[str, str], RelationCandidate],
) -> None:
@@ -373,7 +373,7 @@ class CandidateIndexes:
)
@classmethod
- def from_skills(cls, skills: Iterable[SkillFingerprint]) -> "CandidateIndexes":
+ def from_skills(cls, skills: Iterable[Fingerprint]) -> "CandidateIndexes":
indexes = cls()
for skill in skills:
for output in skill.outputs:
@@ -603,7 +603,7 @@ def _debug_candidate_generated(
_DATA_TYPE_VOCAB = DataTypeVocabulary.default()
-def _skill_terms(skill: SkillFingerprint) -> Set[str]:
+def _skill_terms(skill: Fingerprint) -> Set[str]:
terms: Set[str] = set()
chunks = [skill.id, skill.name, skill.description]
chunks.extend(item.name for item in skill.inputs)
diff --git a/jiuwenswarm/symphony/graph/matcher/cache.py b/jiuwenswarm/symphony/graph/matcher/cache.py
index c03f800099..fdfc07eee0 100644
--- a/jiuwenswarm/symphony/graph/matcher/cache.py
+++ b/jiuwenswarm/symphony/graph/matcher/cache.py
@@ -10,7 +10,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable
-from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint
+from jiuwenswarm.symphony.fingerprint.models import Fingerprint
from jiuwenswarm.symphony.graph.models import LLMMatch, RelationCandidate, SkillRegistry
@@ -29,7 +29,7 @@ class CachedOntologyMatcher:
matcher: Any,
cache_path: str | Path,
*,
- fingerprints: Iterable[SkillFingerprint],
+ fingerprints: Iterable[Fingerprint],
) -> None:
self.matcher = matcher
self.cache = RelationMatchCache(
@@ -125,12 +125,12 @@ class RelationMatchCache:
path: str | Path,
*,
matcher_signature: dict[str, Any],
- fingerprints: Iterable[SkillFingerprint],
+ fingerprints: Iterable[Fingerprint],
) -> None:
self.path = Path(path).resolve()
self.matcher_signature = matcher_signature
self.fingerprint_hashes = {
- item.id: _stable_sha256(item.to_dict())
+ item.id: _stable_sha256(item.graph_identity_dict())
for item in fingerprints
}
self._records = self._load()
diff --git a/jiuwenswarm/symphony/graph/matcher/prompt.py b/jiuwenswarm/symphony/graph/matcher/prompt.py
index f4773c0085..3e0e06581b 100644
--- a/jiuwenswarm/symphony/graph/matcher/prompt.py
+++ b/jiuwenswarm/symphony/graph/matcher/prompt.py
@@ -6,7 +6,7 @@ import hashlib
import json
from typing import Any, Dict, List
-from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint
+from jiuwenswarm.symphony.fingerprint.models import Fingerprint
from jiuwenswarm.symphony.graph.models import (
ALLOWED_RELATION_TYPES,
RelationCandidate,
@@ -56,7 +56,7 @@ def _ordered_skill_ids_for_candidates(
return ordered
-def _skill_context(skill: SkillFingerprint) -> Dict[str, Any]:
+def _skill_context(skill: Fingerprint) -> Dict[str, Any]:
return {
"id": skill.id,
"name": skill.name,
diff --git a/jiuwenswarm/symphony/graph/models.py b/jiuwenswarm/symphony/graph/models.py
index dca3c586ae..09a0e7b415 100644
--- a/jiuwenswarm/symphony/graph/models.py
+++ b/jiuwenswarm/symphony/graph/models.py
@@ -6,7 +6,7 @@ from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
-from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint
+from jiuwenswarm.symphony.fingerprint.models import Fingerprint
ALLOWED_RELATION_TYPES = frozenset(
@@ -42,10 +42,10 @@ class GraphDiagnostic:
class SkillRegistry:
"""Validated Skill registry keyed by Skill ID."""
- skills: Dict[str, SkillFingerprint]
+ skills: Dict[str, Fingerprint]
diagnostics: List[GraphDiagnostic] = field(default_factory=list)
- def ordered_skills(self) -> List[SkillFingerprint]:
+ def ordered_skills(self) -> List[Fingerprint]:
return [self.skills[skill_id] for skill_id in sorted(self.skills)]
@@ -245,7 +245,7 @@ class GraphBuildResult:
"""Complete graph build result."""
manifest: BuildManifest
- skills: List[SkillFingerprint]
+ skills: List[Fingerprint]
candidates: List[RelationCandidate]
llm_matches: List[LLMMatch]
graph: SkillGraph
diff --git a/jiuwenswarm/symphony/graph/pipeline.py b/jiuwenswarm/symphony/graph/pipeline.py
index ffdb059c0d..6fade026a9 100644
--- a/jiuwenswarm/symphony/graph/pipeline.py
+++ b/jiuwenswarm/symphony/graph/pipeline.py
@@ -13,7 +13,7 @@ from jiuwenswarm.symphony.graph.matcher import (
)
from jiuwenswarm.symphony.graph.models import BuildManifest, GraphBuildResult, GraphDiagnostic
from jiuwenswarm.symphony.graph.registry import SkillRegistryBuilder
-from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint
+from jiuwenswarm.symphony.fingerprint.models import Fingerprint
GraphProgress = Callable[..., None]
@@ -38,7 +38,7 @@ class GraphBuilder:
async def __call__(
self,
- fingerprints: Iterable[SkillFingerprint],
+ fingerprints: Iterable[Fingerprint],
*,
progress: GraphProgress | None = None,
) -> GraphBuildResult:
@@ -46,7 +46,7 @@ class GraphBuilder:
async def build(
self,
- fingerprints: Iterable[SkillFingerprint],
+ fingerprints: Iterable[Fingerprint],
*,
progress: GraphProgress | None = None,
) -> GraphBuildResult:
diff --git a/jiuwenswarm/symphony/graph/registry.py b/jiuwenswarm/symphony/graph/registry.py
index b303f59606..a9e0787c98 100644
--- a/jiuwenswarm/symphony/graph/registry.py
+++ b/jiuwenswarm/symphony/graph/registry.py
@@ -5,18 +5,33 @@ from __future__ import annotations
from typing import Iterable, List
from jiuwenswarm.symphony.graph.models import GraphDiagnostic, SkillRegistry
-from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint
+from jiuwenswarm.symphony.fingerprint.models import Fingerprint
class SkillRegistryBuilder:
"""Register normalized Skill fingerprints by stable ID."""
@staticmethod
- def register(fingerprints: Iterable[SkillFingerprint]) -> SkillRegistry:
+ def register(fingerprints: Iterable[Fingerprint]) -> SkillRegistry:
skills = {}
diagnostics: List[GraphDiagnostic] = []
for fingerprint in sorted(fingerprints, key=lambda item: item.id):
+ if fingerprint.type != "skill":
+ diagnostics.append(
+ GraphDiagnostic(
+ stage="registry",
+ severity="error",
+ code="unsupported_fingerprint_type",
+ message=(
+ "Skill Graph only accepts fingerprints with "
+ "type='skill'."
+ ),
+ details={"type": fingerprint.type, "id": fingerprint.id},
+ )
+ )
+ continue
+
if not fingerprint.id:
diagnostics.append(
GraphDiagnostic(
diff --git a/jiuwenswarm/symphony/score_state.py b/jiuwenswarm/symphony/score_state.py
index 70ab8f498f..80050d021c 100644
--- a/jiuwenswarm/symphony/score_state.py
+++ b/jiuwenswarm/symphony/score_state.py
@@ -9,7 +9,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable
-from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint
+from jiuwenswarm.symphony.fingerprint.models import Fingerprint
from jiuwenswarm.symphony.score_storage import resolve_score_artifact_dir
SCORE_STATE_FILENAME = "score_state.json"
@@ -109,7 +109,7 @@ class ScoreStateBuilder:
*,
folders: list[Any],
current_hashes: dict[str, str],
- fingerprints_by_path: dict[str, SkillFingerprint],
+ fingerprints_by_path: dict[str, Fingerprint],
old_state: ScoreState,
removed_paths: set[str],
) -> ScoreState:
@@ -141,8 +141,12 @@ class ScoreStateBuilder:
return ScoreState(skills=entries)
@staticmethod
- def fingerprint_hash(fingerprint: SkillFingerprint) -> str:
- payload = json.dumps(fingerprint.to_dict(), ensure_ascii=False, sort_keys=True)
+ def fingerprint_hash(fingerprint: Fingerprint) -> str:
+ payload = json.dumps(
+ fingerprint.graph_identity_dict(),
+ ensure_ascii=False,
+ sort_keys=True,
+ )
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
@staticmethod
diff --git a/tests/unit_tests/symphony/evaluation/test_artifacts.py b/tests/unit_tests/symphony/evaluation/test_artifacts.py
new file mode 100644
index 0000000000..46c4da4817
--- /dev/null
+++ b/tests/unit_tests/symphony/evaluation/test_artifacts.py
@@ -0,0 +1,338 @@
+from __future__ import annotations
+
+import json
+from datetime import datetime, timezone
+
+import pytest
+
+import jiuwenswarm.symphony.evaluation as evaluation
+import jiuwenswarm.symphony.evaluation.artifacts as artifacts
+
+
+def fingerprint(
+ kind: str = "skill", identifier: str = "weather"
+) -> evaluation.Fingerprint:
+ return evaluation.Fingerprint(
+ type=kind,
+ id=identifier,
+ name=identifier,
+ description="A useful capability description.",
+ version="1.0.0",
+ inputs=[evaluation.ParameterSpec(name="query", type="text")],
+ outputs=[evaluation.ArtifactSpec(name="answer", type="text")],
+ static_data={"secret_source": "private"},
+ )
+
+
+def quality(
+ item: evaluation.Fingerprint,
+ score: float = 1.0,
+ window: evaluation.Window | None = None,
+) -> evaluation.QualityResult:
+ metrics = {
+ name: evaluation.MetricResult(
+ metric=name,
+ type=item.type,
+ id=item.id,
+ version=item.version,
+ event_time=datetime(2026, 7, 18, tzinfo=timezone.utc),
+ score=score,
+ level="excellent" if score == 1 else "pass",
+ reason=f"{name} result",
+ metrics={
+ "result_count": 2,
+ "measured_at": datetime(2026, 7, 18),
+ "quality_score": 0.5,
+ },
+ )
+ for name in (
+ "success_rate",
+ "latency",
+ "accuracy",
+ "completeness",
+ "compliance",
+ )
+ }
+ return evaluation.QualityResult(
+ type=item.type,
+ id=item.id,
+ version=item.version,
+ window=window,
+ result_count=2,
+ metrics=metrics,
+ confidence="normal",
+ )
+
+
+def test_write_quality_report_creates_public_atomic_artifact(tmp_path) -> None:
+ item = fingerprint()
+ window = evaluation.Window(label="daily")
+ target = evaluation.write_quality_report(
+ tmp_path,
+ [item],
+ [quality(item, window=window)],
+ window,
+ )
+
+ payload = json.loads(target.read_text(encoding="utf-8"))
+ assert target == tmp_path / "fingerprints.json"
+ assert payload["window"]["label"] == "daily"
+ assert len(payload["fingerprints"]) == 1
+ written = payload["fingerprints"][0]
+ assert "static_data" not in written
+ assert "quality_score" not in written
+ assert set(written["quality"]) == {
+ "success_rate",
+ "latency",
+ "accuracy",
+ "fluency",
+ "compliance",
+ }
+ assert written["quality"]["accuracy"]["name"] == "准确性"
+ assert written["quality"]["accuracy"]["result_count"] == 2
+ assert "result_count" not in written["quality"]["accuracy"]["metrics"]
+ assert "reason" not in written["quality"]["accuracy"]
+ assert "assertions" not in written["quality"]["accuracy"]
+ assert "evidence" not in written["quality"]["accuracy"]
+ assert {name: value["name"] for name, value in written["quality"].items()} == {
+ "success_rate": "响应完成率",
+ "latency": "响应时延",
+ "accuracy": "准确性",
+ "fluency": "交互流畅性",
+ "compliance": "结构规范性",
+ }
+ latency = written["quality"]["latency"]
+ assert latency["name"] == "响应时延"
+ assert "scenario" in latency
+ assert set(latency["metrics"]) == {
+ "avg_ttft",
+ "p95_ttft",
+ "p99_ttft",
+ "avg_e2e",
+ "p95_e2e",
+ "p99_e2e",
+ }
+ assert list(tmp_path.glob(".fingerprints.json.*.tmp")) == []
+ assert "quality_score" not in target.read_text(encoding="utf-8")
+
+
+def test_write_quality_report_closes_descriptor_when_fdopen_fails(
+ tmp_path,
+ monkeypatch,
+) -> None:
+ item = fingerprint()
+ closed_descriptors = []
+ real_close = artifacts.os.close
+
+ def fail_fdopen(*args, **kwargs):
+ raise OSError("simulated fdopen failure")
+
+ def close_descriptor(descriptor):
+ closed_descriptors.append(descriptor)
+ real_close(descriptor)
+
+ monkeypatch.setattr(artifacts.os, "fdopen", fail_fdopen)
+ monkeypatch.setattr(artifacts.os, "close", close_descriptor)
+
+ with pytest.raises(OSError, match="simulated fdopen failure"):
+ evaluation.write_quality_report(tmp_path, [item], [quality(item)])
+
+ assert len(closed_descriptors) == 1
+ assert list(tmp_path.glob(".fingerprints.json.*.tmp")) == []
+
+
+def test_write_quality_report_updates_by_composite_key_and_keeps_others(
+ tmp_path,
+) -> None:
+ target = tmp_path / "fingerprints.json"
+ target.write_text(
+ json.dumps(
+ {
+ "window": None,
+ "fingerprints": [
+ {
+ "type": "agent",
+ "id": "same",
+ "name": "old-agent",
+ "description": "old",
+ "version": "1.0.0",
+ "inputs": [],
+ "outputs": [],
+ "static_data": {"private": True},
+ "quality_score": 0.5,
+ "quality": {
+ "quality_score": 0.5,
+ "unknown_metric": {"score": 1},
+ },
+ },
+ {
+ "type": "skill",
+ "id": "same",
+ "name": "unrelated-skill",
+ "description": "kept",
+ "version": "1.0.0",
+ "inputs": [],
+ "outputs": [],
+ "quality_score": 0.8,
+ "quality": {
+ name: {
+ "name": name,
+ "score": 1,
+ "level": "excellent",
+ "result_count": 1,
+ "reason": "old",
+ "metrics": {},
+ }
+ for name in (
+ "success_rate",
+ "latency",
+ "accuracy",
+ "fluency",
+ "compliance",
+ "unknown_metric",
+ )
+ },
+ },
+ {
+ "type": "agent",
+ "id": "malformed",
+ "name": "malformed",
+ "description": "kept without malformed quality",
+ "version": "1.0.0",
+ "inputs": [],
+ "outputs": [],
+ "quality_score": 0.1,
+ "quality": {"unknown_metric": {"score": 1}},
+ },
+ ],
+ }
+ ),
+ encoding="utf-8",
+ )
+ agent = fingerprint("agent", "same")
+
+ evaluation.write_quality_report(target, [agent], [quality(agent, 0.9)])
+
+ objects = json.loads(target.read_text(encoding="utf-8"))["fingerprints"]
+ by_key = {(item["type"], item["id"], item["version"]): item for item in objects}
+ assert len(objects) == 3
+ assert by_key[("agent", "same", "1.0.0")]["name"] == "same"
+ assert by_key[("skill", "same", "1.0.0")]["name"] == "unrelated-skill"
+ assert all("static_data" not in item for item in objects)
+ serialized = json.dumps(objects)
+ assert "quality_score" not in serialized
+ assert "quality" not in by_key[("agent", "malformed", "1.0.0")]
+ assert set(by_key[("skill", "same", "1.0.0")]["quality"]) == {
+ "success_rate",
+ "latency",
+ "accuracy",
+ "fluency",
+ "compliance",
+ }
+
+
+def test_quality_without_supplied_fingerprint_is_rejected(tmp_path) -> None:
+ item = fingerprint()
+ with pytest.raises(ValueError, match="no matching fingerprint"):
+ evaluation.write_quality_report(tmp_path, [], [quality(item)])
+
+
+def test_quality_metric_name_must_match_its_mapping_key(tmp_path) -> None:
+ item = fingerprint()
+ result = quality(item)
+ metrics = dict(result.metrics)
+ metrics["completeness"] = metrics["accuracy"]
+ invalid = evaluation.QualityResult(
+ type=result.type,
+ id=result.id,
+ version=result.version,
+ window=result.window,
+ result_count=result.result_count,
+ metrics=metrics,
+ confidence=result.confidence,
+ )
+
+ with pytest.raises(ValueError, match="must match its mapping key"):
+ evaluation.write_quality_report(tmp_path, [item], [invalid])
+
+
+def test_quality_metric_identity_must_match_quality_result(tmp_path) -> None:
+ item = fingerprint()
+ result = quality(item)
+ metrics = dict(result.metrics)
+ accuracy = metrics["accuracy"]
+ metrics["accuracy"] = evaluation.MetricResult(
+ metric=accuracy.metric,
+ type=accuracy.type,
+ id="another-object",
+ version=accuracy.version,
+ event_time=accuracy.event_time,
+ score=accuracy.score,
+ level=accuracy.level,
+ reason=accuracy.reason,
+ metrics=accuracy.metrics,
+ )
+ invalid = evaluation.QualityResult(
+ type=result.type,
+ id=result.id,
+ version=result.version,
+ window=result.window,
+ result_count=result.result_count,
+ metrics=metrics,
+ confidence=result.confidence,
+ )
+
+ with pytest.raises(ValueError, match="must match QualityResult identity"):
+ evaluation.write_quality_report(tmp_path, [item], [invalid])
+
+
+def test_cross_window_update_clears_quality_from_unupdated_objects(tmp_path) -> None:
+ first_window = None
+ second_window = evaluation.Window(label="second")
+ first = fingerprint("agent", "first")
+ untouched = fingerprint("skill", "untouched")
+ evaluation.write_quality_report(
+ tmp_path,
+ [first, untouched],
+ [
+ quality(first, window=first_window),
+ quality(untouched, window=first_window),
+ ],
+ )
+
+ evaluation.write_quality_report(
+ tmp_path,
+ [first],
+ [quality(first, score=0.9, window=second_window)],
+ )
+
+ payload = json.loads((tmp_path / "fingerprints.json").read_text(encoding="utf-8"))
+ by_id = {item["id"]: item for item in payload["fingerprints"]}
+ assert payload["window"]["label"] == "second"
+ assert "quality" in by_id["first"]
+ assert "quality" not in by_id["untouched"]
+ assert by_id["untouched"]["description"] == untouched.description
+
+
+def test_quality_result_windows_must_be_consistent(tmp_path) -> None:
+ first = fingerprint("agent", "first")
+ second = fingerprint("skill", "second")
+ first_window = evaluation.Window(label="first")
+ second_window = evaluation.Window(label="second")
+
+ with pytest.raises(ValueError, match="must be consistent"):
+ evaluation.write_quality_report(
+ tmp_path,
+ [first, second],
+ [
+ quality(first, window=first_window),
+ quality(second, window=second_window),
+ ],
+ )
+ with pytest.raises(ValueError, match="explicit window"):
+ evaluation.write_quality_report(
+ tmp_path,
+ [first],
+ [quality(first, window=first_window)],
+ second_window,
+ )
diff --git a/tests/unit_tests/symphony/evaluation/test_core.py b/tests/unit_tests/symphony/evaluation/test_core.py
new file mode 100644
index 0000000000..355cf42938
--- /dev/null
+++ b/tests/unit_tests/symphony/evaluation/test_core.py
@@ -0,0 +1,593 @@
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any
+
+import pytest
+
+import jiuwenswarm.symphony.evaluation as evaluation
+
+
+def fingerprint(
+ kind: str = "skill", identifier: str = "weather"
+) -> evaluation.Fingerprint:
+ return evaluation.Fingerprint(
+ type=kind,
+ id=identifier,
+ name=identifier,
+ description="Answer weather questions accurately.",
+ version="1.0.0",
+ inputs=[evaluation.ParameterSpec(name="query", type="text")],
+ outputs=[evaluation.ArtifactSpec(name="answer", type="text")],
+ static_data={"documentation": "Return concise current conditions."},
+ )
+
+
+def case(kind: str = "skill", **kwargs: Any) -> evaluation.EvaluationCase:
+ values: dict[str, Any] = {
+ "fingerprint": fingerprint(kind),
+ "message": [
+ {"role": "user", "content": "Weather in Shenzhen?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_weather",
+ "type": "function",
+ "function": {
+ "name": "weather",
+ "arguments": '{"city":"Shenzhen"}',
+ },
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_weather", "content": "30"},
+ {"role": "user", "content": "Use Celsius."},
+ {"role": "assistant", "content": "It is 30 °C."},
+ ],
+ "success": True,
+ "latency": evaluation.Latency(ttft=1_000, e2e=10_000),
+ "event_time": datetime(2026, 7, 18, tzinfo=timezone.utc),
+ }
+ values.update(kwargs)
+ return evaluation.EvaluationCase(**values)
+
+
+def test_agent_and_skill_case_extract_openai_message_values() -> None:
+ skill_case = case()
+ agent_case = case("agent")
+
+ assert skill_case.input_contents == ["Weather in Shenzhen?", "Use Celsius."]
+ assert skill_case.final_output == "It is 30 °C."
+ assert agent_case.fingerprint.type == "agent"
+ assert evaluation.EvaluationCase(fingerprint=fingerprint()).final_output is None
+
+
+def test_latency_validates_invalid_values() -> None:
+ with pytest.raises(ValueError, match="non-negative"):
+ evaluation.Latency(e2e=-1)
+
+
[email protected]("invalid", [float("nan"), float("inf"), float("-inf")])
+def test_latency_rejects_non_finite_values(invalid: float) -> None:
+ with pytest.raises(ValueError, match="finite"):
+ evaluation.Latency(ttft=invalid)
+ with pytest.raises(ValueError, match="finite"):
+ evaluation.Latency(e2e=invalid)
+
+
+def test_success_rate_single_and_grouped_results_exclude_na() -> None:
+ evaluator = evaluation.SuccessRateEvaluator()
+ results = evaluator.evaluate_batch(
+ [case(success=True), case(success=False), case(success=None)]
+ )
+
+ assert [(result.score, result.level) for result in results] == [
+ (1.0, "excellent"),
+ (0.0, "fail"),
+ (None, "not_applicable"),
+ ]
+ aggregate = evaluator.new_accumulator().extend(results).aggregate()[0]
+ assert aggregate.score == 0.5
+ assert aggregate.level == "fail"
+ assert aggregate.reason == ""
+ assert aggregate.metrics["result_count"] == 2
+
+
+ ("value", "level", "score"),
+ [
+ (5_000, "excellent", 1.0),
+ (5_001, "good", 0.8),
+ (10_001, "pass", 0.6),
+ (15_001, "fail", 0.0),
+ ],
+)
+def test_realtime_latency_thresholds(value: float, level: str, score: float) -> None:
+ evaluator = evaluation.LatencyEvaluator("realtime_interaction")
+ result = evaluator.evaluate(case(latency=evaluation.Latency(ttft=value)))
+
+ assert (result.level, result.score) == (level, score)
+
+
+def test_short_and_long_latency_and_missing_data() -> None:
+ short = evaluation.LatencyEvaluator("short_task")
+ long = evaluation.LatencyEvaluator("long")
+
+ assert (
+ short.evaluate(case(latency=evaluation.Latency(e2e=30_000))).level
+ == "excellent"
+ )
+ assert short.evaluate(case(latency=evaluation.Latency(e2e=90_001))).level == "fail"
+ assert (
+ long.evaluate(case(latency=evaluation.Latency(e2e=999_999))).level
+ == "excellent"
+ )
+ assert short.evaluate(case(latency=None)).level == "not_applicable"
+
+
+def test_latency_evaluator_reads_classified_static_scenario() -> None:
+ original = fingerprint()
+ classified = evaluation.LatencyScenarioClassifier(
+ FakeLLM('{"scenario": "realtime_interaction", "reason": "interactive Q&A"}')
+ ).apply(original)
+ evaluator = evaluation.LatencyEvaluator(scenario=None)
+ result = evaluator.evaluate(
+ case(
+ fingerprint=classified,
+ latency=evaluation.Latency(ttft=5_001, e2e=1),
+ )
+ )
+
+ assert "evaluation" not in original.static_data
+ assert result.metrics["scenario"] == "realtime_interaction"
+ assert result.level == "good"
+
+
+def test_latency_scenario_classifier_rejects_invalid_response() -> None:
+ classifier = evaluation.LatencyScenarioClassifier(
+ FakeLLM('{"scenario": "instant", "reason": "unsupported"}')
+ )
+
+ with pytest.raises(ValueError, match="unsupported latency scenario"):
+ classifier.classify(fingerprint())
+
+
+def test_latency_aggregation_reports_both_distributions_and_grades_p95() -> None:
+ evaluator = evaluation.LatencyEvaluator("short_task")
+ results = [
+ evaluator.evaluate(
+ case(latency=evaluation.Latency(ttft=first_response, e2e=total))
+ )
+ for first_response, total in [(100, 10_000), (300, 20_000)]
+ ]
+
+ aggregate = evaluator.new_accumulator().extend(results).aggregate()[0]
+
+ assert aggregate.metrics["ttft"] == {
+ "avg": 200.0,
+ "p95": 290.0,
+ "p99": 298.0,
+ }
+ assert aggregate.metrics["e2e"] == {
+ "avg": 15_000.0,
+ "p95": 19_500.0,
+ "p99": 19_900.0,
+ }
+ assert aggregate.level == "excellent"
+ assert aggregate.reason == ""
+
+
+def test_latency_aggregation_rejects_missing_scenario_distribution() -> None:
+ evaluator = evaluation.LatencyEvaluator("short_task")
+ malformed = evaluation.MetricResult(
+ metric="latency",
+ type="agent",
+ id="agent-a",
+ version="1.0.0",
+ event_time=None,
+ score=1.0,
+ level="excellent",
+ reason="",
+ metrics={"scenario": "short_task", "ttft": None, "e2e": None},
+ )
+
+ with pytest.raises(ValueError, match="required distribution"):
+ evaluator.new_accumulator().add(malformed).aggregate()
+
+
+class FakeLLM:
+ def __init__(self, response: str | Exception) -> None:
+ self.response = response
+ self.messages: Any = None
+
+ def chat(self, messages: Any, **kwargs: Any) -> list[str]:
+ self.messages = messages
+ if isinstance(self.response, Exception):
+ raise self.response
+ return [self.response]
+
+ def generate(self, prompts: Any, **kwargs: Any) -> list[str]:
+ raise AssertionError("Scoring evaluators must use chat.")
+
+
+ ("evaluator_type", "score", "level"),
+ [
+ (evaluation.AccuracyEvaluator, 1, "excellent"),
+ (evaluation.AccuracyEvaluator, 0, "fail"),
+ (evaluation.CompletenessEvaluator, 1, "excellent"),
+ (evaluation.CompletenessEvaluator, 0, "fail"),
+ ],
+)
+def test_llm_metrics_accept_only_binary_scores(
+ evaluator_type: type, score: int, level: str
+) -> None:
+ llm = FakeLLM(f'{{"score": {score}, "reason": "结论正确。"}}')
+
+ result = evaluator_type(llm).evaluate(case())
+
+ assert (result.score, result.level) == (float(score), level)
+ assert "static_data" in llm.messages[0]["content"]
+ assert "Use Celsius" in llm.messages[0]["content"]
+ assert "call_weather" in llm.messages[0]["content"]
+
+
+ ("evaluator_type", "rubric_terms"),
+ [
+ (
+ evaluation.AccuracyEvaluator,
+ (
+ "无事实性错误,核心信息准确",
+ "完全符合客观事实,无任何事实性错误",
+ "逻辑严密,推理严谨,无逻辑谬误",
+ "符合行业规范/专业规范,表述专业",
+ "新知识/新产品场景",
+ "事实核查",
+ "逻辑验证",
+ "专业规范",
+ "新知识处理",
+ "只要存在事实性错误即判定为不及格",
+ ),
+ ),
+ (
+ evaluation.CompletenessEvaluator,
+ (
+ "完整执行了用户请求的技能",
+ "从识别意图到执行技能的完整过程",
+ "声称具备的技能与实际执行能力一致",
+ "查询航班、预订服务",
+ "仅提供路径规划但未启动导航",
+ "订票、导航、预订、支付",
+ "功能执行",
+ "流程完整性",
+ "多步骤任务",
+ "技能一致性",
+ "重点关注技能描述中明确提到的步骤和要求",
+ ),
+ ),
+ ],
+)
+def test_llm_metric_prompt_uses_concise_binary_rubric(
+ evaluator_type: type, rubric_terms: tuple[str, ...]
+) -> None:
+ evaluator = evaluator_type(FakeLLM('{"score": 1, "reason": "已完成。"}'))
+
+ result = evaluator.evaluate(case())
+
+ prompt = evaluator.llm.messages[0]["content"]
+ assert result.metric == evaluator.metric
+ assert hasattr(evaluator, "rubric")
+ assert not hasattr(evaluator, "instruction")
+ assert all(term in evaluator.rubric for term in rubric_terms)
+ assert evaluator.rubric in prompt
+ assert "数字 0 或 1" in prompt
+ assert "一句简短理由" in prompt
+ assert "不要输出思考过程" in prompt
+ assert "只返回 JSON" in prompt
+
+
+ "llm",
+ [
+ None,
+ FakeLLM(RuntimeError("offline")),
+ FakeLLM("not json"),
+ FakeLLM("{score: 1, reason: ok}"),
+ FakeLLM('result: {"score": 1, "reason": "ok"}'),
+ FakeLLM('{"score": 2, "reason": "bad"}'),
+ FakeLLM('{"score": 0.5, "reason": "uncertain"}'),
+ FakeLLM('{"score": "1", "reason": "bad type"}'),
+ FakeLLM('{"score": true, "reason": "bad type"}'),
+ FakeLLM('{"score": 0.9}'),
+ ],
+)
+def test_llm_metric_failures_are_not_applicable(llm: FakeLLM | None) -> None:
+ assert evaluation.AccuracyEvaluator(llm).evaluate(case()).level == "not_applicable"
+
+
+def test_llm_metric_missing_input_or_output_is_not_applicable() -> None:
+ evaluator = evaluation.AccuracyEvaluator(FakeLLM('{"score": 1, "reason": "ok"}'))
+ no_input = case(message=[{"role": "assistant", "content": "x"}])
+ no_output = case(message=[{"role": "user", "content": "x"}])
+
+ assert evaluator.evaluate(no_input).level == "not_applicable"
+ assert evaluator.evaluate(no_output).level == "not_applicable"
+
+
+ ("evaluator_type", "passed", "total", "expected_score", "expected_level"),
+ [
+ (evaluation.AccuracyEvaluator, 8, 10, 0.8, "fail"),
+ (evaluation.AccuracyEvaluator, 9, 10, 0.9, "pass"),
+ (evaluation.AccuracyEvaluator, 19, 20, 0.95, "good"),
+ (evaluation.AccuracyEvaluator, 99, 100, 0.99, "excellent"),
+ (evaluation.CompletenessEvaluator, 5, 10, 0.5, "fail"),
+ (evaluation.CompletenessEvaluator, 6, 10, 0.6, "pass"),
+ (evaluation.CompletenessEvaluator, 8, 10, 0.8, "good"),
+ (evaluation.CompletenessEvaluator, 9, 10, 0.9, "excellent"),
+ ],
+)
+def test_binary_metric_aggregation_uses_metric_thresholds(
+ evaluator_type: type,
+ passed: int,
+ total: int,
+ expected_score: float,
+ expected_level: str,
+) -> None:
+ evaluator = evaluator_type(FakeLLM('{"score": 1, "reason": "通过。"}'))
+ successful = evaluator.evaluate(case())
+ evaluator.llm = FakeLLM('{"score": 0, "reason": "未通过。"}')
+ failed = evaluator.evaluate(case())
+ results = [successful] * passed + [failed] * (total - passed)
+
+ aggregate = evaluator.new_accumulator().extend(results).aggregate()[0]
+
+ assert aggregate.score == pytest.approx(expected_score)
+ assert aggregate.level == expected_level
+ assert aggregate.reason == ""
+
+
+@dataclass
+class Rule:
+ code: str
+ severity: evaluation.ComplianceSeverity
+ passed: bool = False
+ raises: bool = False
+
+ def evaluate(
+ self, fingerprint: evaluation.Fingerprint
+ ) -> evaluation.AssertionResult:
+ if self.raises:
+ raise RuntimeError("broken rule")
+ return evaluation.AssertionResult(
+ code="ignored",
+ passed=self.passed,
+ severity="hard",
+ reason=fingerprint.name,
+ evidence=[{"rule": self.code}],
+ )
+
+
+ ("rules", "expected"),
+ [
+ ([Rule("ok", "hard", True)], (1.0, "excellent")),
+ ([Rule("light", "light")], (0.8, "good")),
+ ([Rule("major", "major")], (0.6, "pass")),
+ ([Rule("hard", "hard")], (0.0, "fail")),
+ ([Rule("raises", "light", raises=True)], (0.0, "fail")),
+ ],
+)
+def test_compliance_severity(rules: list[Rule], expected: tuple[float, str]) -> None:
+ result = evaluation.ComplianceEvaluator(rules).evaluate(case())
+ assert (result.score, result.level) == expected
+
+
+def test_compliance_without_rules_is_not_applicable() -> None:
+ result = evaluation.ComplianceEvaluator().evaluate(case())
+ assert result.level == "not_applicable"
+
+
+def test_compliance_rejects_unknown_severity() -> None:
+ rule = Rule("unknown", "warning")
+ with pytest.raises(ValueError, match="Unsupported compliance severity"):
+ evaluation.ComplianceEvaluator([rule])
+
+
+def test_compliance_isolates_invalid_rule_result_as_hard_failure() -> None:
+ class InvalidRule:
+ code = "invalid-result"
+ severity = "light"
+
+ def evaluate(self, fingerprint: evaluation.Fingerprint) -> object:
+ return object()
+
+ result = evaluation.ComplianceEvaluator([InvalidRule()]).evaluate(case())
+
+ assert (result.score, result.level) == (0.0, "fail")
+
+
+def test_assertion_result_rejects_unknown_severity() -> None:
+ with pytest.raises(ValueError, match="severity"):
+ evaluation.AssertionResult(
+ code="bad",
+ passed=False,
+ severity="warning",
+ )
+
+
+def test_result_models_recursively_convert_dates_to_json_safe_values() -> None:
+ timestamp = datetime(2026, 7, 18, 8, 30, tzinfo=timezone.utc)
+ metric = evaluation.MetricResult(
+ metric="accuracy",
+ type="skill",
+ id="weather",
+ version="1.0.0",
+ event_time=timestamp,
+ score=1.0,
+ level="excellent",
+ reason="ok",
+ metrics={"nested": [{"measured_at": timestamp}]},
+ )
+ window = evaluation.Window(start=timestamp, end=timestamp, label="sample")
+ quality = evaluation.QualityResult(
+ type="skill",
+ id="weather",
+ version="1.0.0",
+ window=window,
+ result_count=1,
+ metrics={"accuracy": metric},
+ confidence="low",
+ )
+
+ payload = quality.to_dict()
+ assert payload["metrics"]["accuracy"]["event_time"] == timestamp.isoformat()
+ assert (
+ payload["metrics"]["accuracy"]["metrics"]["nested"][0]["measured_at"]
+ == timestamp.isoformat()
+ )
+ json.dumps(payload, allow_nan=False)
+
+
+def test_public_result_models_do_not_expose_assertions_or_evidence() -> None:
+ metric = evaluation.MetricResult(
+ metric="accuracy",
+ type="agent",
+ id="weather",
+ version="1",
+ event_time=None,
+ score=1.0,
+ level="excellent",
+ reason="ok",
+ )
+ quality = evaluation.QualityResult(
+ type="agent",
+ id="weather",
+ version="1",
+ window=None,
+ result_count=1,
+ metrics={"accuracy": metric},
+ confidence="low",
+ )
+
+ assert not hasattr(metric, "assertions")
+ assert not hasattr(metric, "evidence")
+ assert not hasattr(quality, "evidence")
+ assert "assertions" not in metric.to_dict()
+ assert "evidence" not in metric.to_dict()
+ assert metric.to_dict()["reason"] == "ok"
+ assert "evidence" not in quality.to_dict()
+ assert "reasons" not in quality.to_dict()
+ assert "reason" not in quality.to_dict()["metrics"]["accuracy"]
+
+
[email protected]("invalid", [float("nan"), float("inf"), float("-inf")])
+def test_result_models_reject_non_finite_nested_numbers(invalid: float) -> None:
+ result = evaluation.MetricResult(
+ metric="accuracy",
+ type="skill",
+ id="weather",
+ version="1.0.0",
+ event_time=None,
+ score=1.0,
+ level="excellent",
+ reason="ok",
+ metrics={"distribution": [invalid]},
+ )
+ with pytest.raises(ValueError, match="finite"):
+ result.to_dict()
+
+
+def test_result_models_reject_unknown_nested_objects() -> None:
+ assertion = evaluation.AssertionResult(
+ code="unknown",
+ passed=True,
+ evidence=[{"value": object()}],
+ )
+ with pytest.raises(TypeError, match="not JSON serializable"):
+ assertion.to_dict()
+
+
+def test_compliance_aggregation_keeps_one_static_result() -> None:
+ evaluator = evaluation.ComplianceEvaluator([Rule("static", "light")])
+ result = evaluator.evaluate(case())
+
+ aggregate = evaluator.new_accumulator().extend([result, result]).aggregate()[0]
+
+ assert aggregate.metrics["result_count"] == 1
+ assert aggregate.score == result.score
+ assert aggregate.reason == ""
+ assert not hasattr(aggregate, "assertions")
+ assert not hasattr(aggregate, "evidence")
+
+
+def standard_suite() -> evaluation.EvaluationSuite:
+ score_llm = FakeLLM('{"score": 1, "reason": "ok"}')
+ return evaluation.EvaluationSuite(
+ [
+ evaluation.SuccessRateEvaluator(),
+ evaluation.LatencyEvaluator(),
+ evaluation.AccuracyEvaluator(score_llm),
+ evaluation.CompletenessEvaluator(score_llm),
+ evaluation.ComplianceEvaluator([Rule("ok", "hard", True)]),
+ ]
+ )
+
+
+def test_suite_batch_and_quality_result_have_no_quality_score() -> None:
+ suite = standard_suite()
+ batches = suite.evaluate_batch([case(), case(kind="agent")])
+ accumulator = suite.new_accumulator(evaluation.Window(label="daily"))
+ quality = accumulator.extend(batches).aggregate()
+
+ assert len(batches) == 2
+ assert [result.type for result in quality] == ["agent", "skill"]
+ assert quality[0].confidence == "low"
+ assert set(quality[0].metrics) == {
+ "success_rate",
+ "latency",
+ "accuracy",
+ "completeness",
+ "compliance",
+ }
+ assert "quality_score" not in quality[0].to_dict()
+ assert quality[0].to_dict()["window"]["label"] == "daily"
+
+
+def test_all_na_quality_result_has_zero_count_and_no_confidence() -> None:
+ suite = evaluation.EvaluationSuite()
+ result = suite.evaluate(case(success=None, latency=None, message=[]))
+ quality = suite.new_accumulator().add(result).aggregate()[0]
+
+ assert quality.result_count == 0
+ assert quality.confidence == "none"
+ assert quality.metrics["success_rate"].score is None
+
+
+def test_suite_requires_atomic_five_metric_results_with_one_identity() -> None:
+ with pytest.raises(ValueError, match="exactly the five"):
+ evaluation.EvaluationSuite([evaluation.SuccessRateEvaluator()])
+
+ suite = standard_suite()
+ skill_results = suite.evaluate(case())
+ accumulator = suite.new_accumulator()
+ with pytest.raises(ValueError, match="all five metrics"):
+ accumulator.add({"success_rate": skill_results["success_rate"]})
+
+ agent_results = suite.evaluate(case(kind="agent"))
+ mixed = dict(skill_results)
+ mixed["accuracy"] = agent_results["accuracy"]
+ with pytest.raises(ValueError, match="one fingerprint identity"):
+ accumulator.add(mixed)
+
+ mismatched_metric = dict(skill_results)
+ mismatched_metric["accuracy"] = skill_results["completeness"]
+ with pytest.raises(ValueError, match="mapping key"):
+ accumulator.add(mismatched_metric)
+
+ assert accumulator.aggregate() == []
diff --git a/tests/unit_tests/symphony/evaluation/test_imports.py b/tests/unit_tests/symphony/evaluation/test_imports.py
new file mode 100644
index 0000000000..75b72cd952
--- /dev/null
+++ b/tests/unit_tests/symphony/evaluation/test_imports.py
@@ -0,0 +1,34 @@
+import jiuwenswarm.symphony.evaluation as evaluation
+
+
+def test_public_api_exports_unified_evaluation_contract() -> None:
+ expected = {
+ "AccuracyEvaluator",
+ "ArtifactSpec",
+ "AssertionResult",
+ "ComplianceEvaluator",
+ "ComplianceRule",
+ "CompletenessEvaluator",
+ "EvaluationAccumulator",
+ "EvaluationCase",
+ "EvaluationLLM",
+ "EvaluationSuite",
+ "Fingerprint",
+ "Latency",
+ "LatencyEvaluator",
+ "MetricAccumulator",
+ "MetricResult",
+ "ParameterSpec",
+ "QualityResult",
+ "SuccessRateEvaluator",
+ "Window",
+ "write_quality_report",
+ "to_json_safe",
+ }
+
+ assert expected <= set(evaluation.__all__)
+ assert not hasattr(evaluation, "SkillStaticEvaluator")
+ assert not hasattr(evaluation, "SkillDynamicEvaluator")
+ assert not hasattr(evaluation, "EvaluationSubject")
+ assert not hasattr(evaluation, "TraceEvent")
+ assert not hasattr(evaluation, "FluencyEvaluator")
diff --git a/tests/unit_tests/symphony/test_fingerprint_models.py b/tests/unit_tests/symphony/test_fingerprint_models.py
new file mode 100644
index 0000000000..f5dc596e50
--- /dev/null
+++ b/tests/unit_tests/symphony/test_fingerprint_models.py
@@ -0,0 +1,156 @@
+"""Tests for unified Agent and Skill fingerprints."""
+
+import pytest
+
+from jiuwenswarm.symphony.fingerprint import (
+ ArtifactSpec,
+ Fingerprint,
+ ParameterSpec,
+)
+from jiuwenswarm.symphony.graph.matcher.cache import RelationMatchCache
+from jiuwenswarm.symphony.graph.models import LLMMatch, RelationCandidate
+from jiuwenswarm.symphony.graph.registry import SkillRegistryBuilder
+from jiuwenswarm.symphony.score_state import ScoreStateBuilder
+
+
+def _fingerprint(**overrides):
+ values = {
+ "type": "skill",
+ "id": "weather",
+ "name": "Weather",
+ "description": "Get weather forecasts.",
+ "version": "1.0.0",
+ "inputs": [ParameterSpec(name="city", type="text")],
+ "outputs": [ArtifactSpec(name="forecast", type="text")],
+ "static_data": {"documentation": "Weather service"},
+ }
+ values.update(overrides)
+ return Fingerprint(**values)
+
+
+def test_fingerprint_round_trip_preserves_unified_fields():
+ fingerprint = _fingerprint(type="agent")
+
+ assert Fingerprint.from_dict(fingerprint.to_dict()) == fingerprint
+
+
+def test_fingerprint_rejects_unknown_type():
+ with pytest.raises(ValueError, match="agent.*skill"):
+ _fingerprint(type="workflow")
+
+ with pytest.raises(ValueError, match="agent.*skill"):
+ Fingerprint.from_dict({"type": "workflow"})
+
+
[email protected]("field", ["id", "name", "version"])
+def test_fingerprint_rejects_empty_identity_fields(field):
+ with pytest.raises(ValueError, match=field):
+ _fingerprint(**{field: " "})
+
+ payload = _fingerprint().to_dict()
+ payload[field] = ""
+ with pytest.raises(ValueError, match=field):
+ Fingerprint.from_dict(payload)
+
+
[email protected]("field", ["id", "name", "version"])
+def test_fingerprint_rejects_non_string_identity_fields(field):
+ with pytest.raises(ValueError, match=field):
+ _fingerprint(**{field: 1})
+
+ payload = _fingerprint().to_dict()
+ payload[field] = 1
+ with pytest.raises(ValueError, match=field):
+ Fingerprint.from_dict(payload)
+
+
+def test_fingerprint_validates_nested_types_and_static_data():
+ with pytest.raises(ValueError, match="ParameterSpec"):
+ _fingerprint(inputs=[{"name": "city", "type": "text"}])
+ with pytest.raises(ValueError, match="ArtifactSpec"):
+ _fingerprint(outputs=[{"name": "answer", "type": "text"}])
+ with pytest.raises(ValueError, match="static_data"):
+ _fingerprint(static_data=[])
+
+
+ ("field", "value", "message"),
+ [
+ ("inputs", {}, "inputs must be a list"),
+ ("inputs", ["bad"], "inputs must contain dictionaries"),
+ ("outputs", {}, "outputs must be a list"),
+ ("outputs", ["bad"], "outputs must contain dictionaries"),
+ ("static_data", [], "static_data must be a dictionary"),
+ ],
+)
+def test_fingerprint_from_dict_rejects_invalid_collections(field, value, message):
+ payload = _fingerprint().to_dict()
+ payload[field] = value
+
+ with pytest.raises(ValueError, match=message):
+ Fingerprint.from_dict(payload)
+
+
+def test_graph_identity_excludes_static_data_and_hash_is_stable():
+ first = _fingerprint(static_data={"documentation": "first"})
+ second = _fingerprint(static_data={"documentation": "second"})
+
+ assert "static_data" not in first.graph_identity_dict()
+ assert first.graph_identity_dict() == second.graph_identity_dict()
+ assert ScoreStateBuilder.fingerprint_hash(
+ first
+ ) == ScoreStateBuilder.fingerprint_hash(second)
+
+
+def test_skill_registry_rejects_agent_fingerprint():
+ registry = SkillRegistryBuilder.register([_fingerprint(type="agent")])
+
+ assert registry.skills == {}
+ assert [item.code for item in registry.diagnostics] == [
+ "unsupported_fingerprint_type"
+ ]
+
+
+def test_relation_cache_ignores_static_data_changes(tmp_path):
+ candidate = RelationCandidate(
+ source_id="weather",
+ target_id="summary",
+ relation_hints=["exact_io"],
+ candidate_methods=["exact_io"],
+ priority="high",
+ )
+ match = LLMMatch(
+ source_id="weather",
+ target_id="summary",
+ relation_type="can_feed",
+ confidence=1.0,
+ method="test",
+ candidate_id=candidate.key,
+ accepted=True,
+ )
+ target = _fingerprint(
+ id="summary",
+ name="Summary",
+ static_data={"documentation": "first"},
+ )
+ cache_path = tmp_path / "relations.json"
+ first_cache = RelationMatchCache(
+ cache_path,
+ matcher_signature={"matcher": "test"},
+ fingerprints=[_fingerprint(), target],
+ )
+ first_cache.store(candidate, [match])
+ first_cache.flush()
+
+ changed_target = _fingerprint(
+ id="summary",
+ name="Summary",
+ static_data={"documentation": "second"},
+ )
+ second_cache = RelationMatchCache(
+ cache_path,
+ matcher_signature={"matcher": "test"},
+ fingerprints=[_fingerprint(), changed_target],
+ )
+
+ assert second_cache.load(candidate) == [match]
diff --git a/tests/unit_tests/symphony/test_graph_exact_io.py b/tests/unit_tests/symphony/test_graph_exact_io.py
index 6376a85b88..d3250cc458 100644
--- a/tests/unit_tests/symphony/test_graph_exact_io.py
+++ b/tests/unit_tests/symphony/test_graph_exact_io.py
@@ -3,7 +3,7 @@ import pytest
from jiuwenswarm.symphony.fingerprint.models import (
ArtifactSpec,
ParameterSpec,
- SkillFingerprint,
+ Fingerprint,
)
from jiuwenswarm.symphony.graph.builders import ScoreLookupBuilder
from jiuwenswarm.symphony.graph.candidates import CandidateGenerator
@@ -629,7 +629,7 @@ def test_score_lookup_emits_text_term_lookup():
}
-def _candidates(*skills: SkillFingerprint):
+def _candidates(*skills: Fingerprint):
return CandidateGenerator().generate(
SkillRegistry(skills={skill.id: skill for skill in skills})
)
@@ -640,8 +640,9 @@ def _skill(
*,
inputs: list[ParameterSpec] | None = None,
outputs: list[ArtifactSpec] | None = None,
-) -> SkillFingerprint:
- return SkillFingerprint(
+) -> Fingerprint:
+ return Fingerprint(
+ type="skill",
id=skill_id,
name=skill_id,
description="",
diff --git a/tests/unit_tests/symphony/test_graph_service.py b/tests/unit_tests/symphony/test_graph_service.py
index ca767f0ca1..c7b75e88bd 100644
--- a/tests/unit_tests/symphony/test_graph_service.py
+++ b/tests/unit_tests/symphony/test_graph_service.py
@@ -8,7 +8,7 @@ from jiuwenswarm.symphony.fingerprint.models import (
ExtractedSkillSchema,
ParameterSpec,
RawSkillManifest,
- SkillFingerprint,
+ Fingerprint,
SkillFolder,
)
from jiuwenswarm.symphony.fingerprint.normalize import (
@@ -507,7 +507,8 @@ async def test_graph_matcher_uses_low_reasoning_for_forward_and_reverse(monkeypa
)
registry = SkillRegistry(
skills={
- "source": SkillFingerprint(
+ "source": Fingerprint(
+ type="skill",
id="source",
name="Source",
description="Produces result",
@@ -515,7 +516,8 @@ async def test_graph_matcher_uses_low_reasoning_for_forward_and_reverse(monkeypa
inputs=[],
outputs=[ArtifactSpec(name="result", type="text")],
),
- "target": SkillFingerprint(
+ "target": Fingerprint(
+ type="skill",
id="target",
name="Target",
description="Consumes input",
@@ -1340,7 +1342,8 @@ async def test_normalized_calendar_memo_input_enables_expected_candidates(tmp_pa
registry = SkillRegistry(
skills={
calendar_result.fingerprint.id: calendar_result.fingerprint,
- "speech-to-text": SkillFingerprint(
+ "speech-to-text": Fingerprint(
+ type="skill",
id="speech-to-text",
name="speech-to-text",
description="Transcribe audio to text.",
@@ -1348,7 +1351,8 @@ async def test_normalized_calendar_memo_input_enables_expected_candidates(tmp_pa
inputs=[ParameterSpec(name="audio", type="audio")],
outputs=[ArtifactSpec(name="text", type="text")],
),
- "general-writing": SkillFingerprint(
+ "general-writing": Fingerprint(
+ type="skill",
id="general-writing",
name="general-writing",
description="Write markdown content.",
@@ -1732,7 +1736,8 @@ async def test_fingerprint_extractor_extract_from_root_reports_removed_paths_and
@pytest.mark.asyncio
async def test_graph_builder_call_emits_progress_and_supports_no_progress():
fingerprints = [
- SkillFingerprint(
+ Fingerprint(
+ type="skill",
id="skill-1",
name="Skill 1",
description="Test skill",