diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index dd56d26f005..98ba649630f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] +- [新功能] 支持 Multi-Agent 分阶段轨迹评估:保留既有扁平工具指标并增加阶段快照、局部/累计步数、完成/失败/跳过状态与可选期望阶段命中率,单 Agent 输出保持兼容(Refs #2347)。 +- [修复] Multi-Agent 各阶段的 `tool_metrics` 仅统计阶段本地调用,不再将样例级工具期望和步数预算错误应用到每个阶段。 +- [修复] Multi-Agent 顶层轨迹步数改由阶段快照累计,避免将 orchestrator 阶段数误判为 agent-loop 步数并漏报全局预算超限。 - [新功能] Web/API runtime scheduler 硬超时后扫描已落库分析历史,**默认发送**部分完成通知(`DSA_TIMEOUT_PARTIAL_NOTIFY` 未设置或为 true;此前超时不推送已落库个股),并在 `last_error` 中记录 `completed/pending` 摘要;可用 `DSA_TIMEOUT_PARTIAL_NOTIFY=false` 关闭推送(Refs #2328)。 - [测试] 修复股票名称解析冷启动超时并发测试的同步竞态:在放行后台抓取前确认两个等待者均已结束并返回空结果,避免 Docker 发布门禁偶发失败。 - [文档] 将仓库内所有 SerpApi 链接统一更新为新的赞助转化追踪地址。 diff --git a/docs/agent-trajectory-eval.md b/docs/agent-trajectory-eval.md index 8a322a83486..0a567ca1041 100644 --- a/docs/agent-trajectory-eval.md +++ b/docs/agent-trajectory-eval.md @@ -6,7 +6,7 @@ - 指标层(`metrics.py`)是纯函数:只消费轨迹日志与 golden 样例,不 import `src/`,不触网、不调 LLM,可离线单测。 - 入口(`run_eval.py`)通过 `build_agent_executor()` 构建真实执行器,与 `src/core/pipeline.py` 使用同一个执行捕获钩子,消费真实产物。 -- 入口只支持**单 agent 运行**(`AGENT_ARCH=single`,默认):`AGENT_ARCH=multi` 时 factory 返回 orchestrator,其轨迹是各 stage 局部步号的拼接、`total_steps` 为 stage 数,与单 runner 指标契约不兼容——入口在构建前明确报错并退出(退出码 1)。 +- 入口支持**单 agent 与多 Agent 运行**(`AGENT_ARCH=single|multi`,默认仍为 single):多 Agent 结果保留原有扁平 `tool_calls_log` 指标,并通过显式 `stage_trajectories` 快照增加阶段状态与局部/累计步数报告。没有阶段快照时,单 agent 命令与 JSON 结构保持不变。 - 入口用真实工具注册表校验 golden:`expected_tools` 拼错或过期会被判为无效样例(退出码 1),而不是静默按低命中继续评分。 - 本次冻结**最小指标契约**,股票 guard、Codex `arguments_summary` 等扩展语义明确留给后续 PR(见文末「不在范围」)。 @@ -28,7 +28,7 @@ python evals/agent_trajectory/run_eval.py --all --json-out eval_report.json | `--golden-path PATH` | 自定义 golden JSON 路径(默认模块旁 `golden_samples.json`) | | `--json-out PATH` | 写结构化 JSON 报告(`--all` 时为键控对象) | -退出码:`0` 运行成功(含违规);`1` golden 加载(含 `expected_tools` 不在真实工具注册表)/ 样例选择 / 工具注册表加载失败 / 执行器构建(含 `AGENT_ARCH=multi` 拒绝)/ 运行失败(含执行器返回 `success=false`,如 provider 未配置、LLM 错误、超时、max_steps 耗尽、dashboard 解析失败);`2` 用法错误。 +退出码:`0` 运行成功(含违规);`1` golden 加载(含 `expected_tools` 不在真实工具注册表)/ 样例选择 / 工具注册表加载失败 / 执行器构建 / 运行失败(含执行器返回 `success=false`,如 provider 未配置、LLM 错误、超时、max_steps 耗尽、dashboard 解析失败);`2` 用法错误。Multi-Agent 结果若在失败时带有阶段快照,入口会先输出并写入可检查的失败轨迹报告,再以退出码 `1` 表示运行失败;单 Agent 失败行为不变。 ## 冻结的最小指标契约 @@ -44,6 +44,30 @@ python evals/agent_trajectory/run_eval.py --all --json-out eval_report.json | `cached_calls` | `cached=true` 的条目数(runner 语义:复用不可重试的失败结果) | | `distinct_steps` / `max_steps_touched` | 日志 step 与 `AgentResult.total_steps` 取较大者(最后纯回答轮不产生工具调用,日志会低估);`max_steps_touched` 为 `max(step) >= allowed_max_steps` 的启发式 | +## Multi-Agent 阶段轨迹 + +当执行器结果携带非空 `stage_trajectories` 时,入口在上述工具指标之外输出 `stage_metrics`。每个阶段快照是稳定的 JSON-safe 白名单对象: + +| 字段 | 说明 | +| --- | --- | +| `stage_name` | 阶段或 specialist 名称 | +| `status` | `completed` / `failed` / `skipped` 等阶段状态 | +| `total_steps` | 该阶段自己的局部 agent-loop 步数,不是全局阶段计数 | +| `tool_calls_log` | 该阶段的原始工具调用日志;空日志也会保留阶段 | +| `failure_reason` | `stage_failure` / `timeout` / `budget_skip` 等降级原因 | + +评估层按快照列表顺序把局部步数累加为 `cumulative_steps`,因此不同阶段从 1 重新计步不会碰撞。该累计值也作为整条 Multi-Agent 轨迹的 agent-loop 步数传给顶层指标;`AgentResult.total_steps` 在 orchestrator 中保留原有阶段数语义,不用于轨迹 loop 预算评分。报告同时包含期望阶段命中率、缺失/额外阶段、完成/失败/跳过计数,以及每个阶段的状态、失败原因、局部/累计步数和工具调用/失败/重试指标。阶段 `tool_metrics` 仅统计该阶段日志中的调用数、工具名、冗余、缓存、失败和重试,不含期望工具命中率、缺失工具、期望外工具违规或 max-steps 违规。Golden 的 `expected_tools`、`allow_optional_tools`、`allowed_max_steps` 属于整条样例,只对汇总工具轨迹评估一次;当前不支持按阶段定义工具合规期望。关键阶段失败后,仍使用已返回的快照生成阶段报告;配置了 `expected_stages` 时,尚未执行的后续阶段会列入缺失阶段。specialist 并发执行后的快照由 scheduler 恢复为选中顺序,不依赖完成先后。 + +golden 样例可选增加 `expected_stages` 字段: + +```json +{ + "expected_stages": ["technical", "intel", "decision"] +} +``` + +未配置时仍会报告实际阶段和状态,但阶段命中率显示为未配置;这不会改变现有单 agent 样例的 JSON 字段。 + ## Golden 样例 schema `golden_samples.json` 是一个数组,字段: @@ -56,6 +80,7 @@ python evals/agent_trajectory/run_eval.py --all --json-out eval_report.json | `expected_tools` | string[] | 期望工具名(必填,非空、无重复) | | `allowed_max_steps` | int | 步数预算启发式(默认 10,>= 1) | | `allow_optional_tools` | bool | 是否容忍期望外工具(默认 true) | +| `expected_stages` | string[] | 多 Agent 阶段期望列表(可选、非空名称且不重复);用于统计命中与缺失阶段 | 校验:加载路径(`load_golden_samples`)直接拒绝非法样例;直接构造路径(`compute_trajectory_metrics`)以 validator 完全相同的措辞逐条上报违规,两条路径的契约按构造保持一致。`known_tool_names` 可注入真实工具注册表做成员校验(metrics 层自身不 import `src/`);`run_eval.py` 入口会自动注入真实工具注册表。 @@ -75,8 +100,10 @@ python evals/agent_trajectory/run_eval.py --all --json-out eval_report.json `--all --json-out` 时外层为 `{sample_id: <上述对象>}` 键控对象。 +含阶段快照的多 Agent 报告会在上述对象中追加 `run_status` (`completed` / `failed`) 与 `stage_metrics` 字段;原有 `metrics` 字段继续表示扁平工具轨迹指标。运行失败但携带阶段快照时,JSON 报告仍会写出,进程退出码为 1。 + ## 不在范围(后续 PR) - 股票维度命中判定与 guard 拦截语义(`guarded` / 越界调用违规) - Codex App Server 的 `arguments_summary` 方言识别 -- 任何 `.env` / 运行时配置与 CI 门禁(本 PR 零 `src/` 改动,不影响现有分析流程) +- 任何 `.env` / 运行时配置与 CI 门禁(本 PR 不改变现有分析流程、调度语义或 CI 阻断规则) diff --git a/evals/agent_trajectory/metrics.py b/evals/agent_trajectory/metrics.py index b3365ca1784..3d38cd68a65 100644 --- a/evals/agent_trajectory/metrics.py +++ b/evals/agent_trajectory/metrics.py @@ -69,7 +69,7 @@ from __future__ import annotations import json -from dataclasses import dataclass, fields +from dataclasses import asdict, dataclass, field, fields from pathlib import Path from typing import Any, Dict, Iterable, List, Optional @@ -91,6 +91,9 @@ class GoldenSample: stock_code: str = "" allowed_max_steps: int = 10 allow_optional_tools: bool = True + # Optional expectation for the multi-agent stage-aware reporter. An + # empty list keeps existing single-agent samples and their reports intact. + expected_stages: List[str] = field(default_factory=list) @dataclass @@ -110,6 +113,37 @@ class TrajectoryMetrics: violations: List[str] +@dataclass +class StageTrajectoryMetrics: + """Metrics for a whitelisted multi-agent stage trajectory.""" + + expected_stage_hit_rate: Optional[float] + expected_total: int + missing_expected_stages: List[str] + unexpected_stages: List[str] + observed_stages: List[str] + completed_stages: int + failed_stages: int + skipped_stages: int + cumulative_steps: int + stage_metrics: List[Dict[str, Any]] + violations: List[str] + + +@dataclass +class _ToolLogMetrics: + """Counts derived only from one tool log, without golden expectations.""" + + tool_calls: int + used_tools: List[str] + redundant_calls: int + cached_calls: int + failed_calls: int + retries: int + distinct_steps: int + max_step: int + + def _args_key(arguments: Any) -> str: """Return a stable idempotency key for tool-call arguments (see module docstring). @@ -140,6 +174,65 @@ def _coerce_step(value: Any) -> int: return step if step > 0 else 0 +def _compute_tool_log_metrics( + log: List[Dict[str, Any]], + total_steps: Optional[int] = None, +) -> _ToolLogMetrics: + """Count call-local facts without applying sample-level expectations.""" + used_tools: List[str] = [] + key_counts: Dict[tuple, int] = {} + key_failed_seen: Dict[tuple, bool] = {} + key_retries: Dict[tuple, int] = {} + failed_calls = cached_calls = redundant_calls = tool_calls = 0 + distinct_steps = max_step = 0 + seen_steps: set = set() + + for entry in log: + if not isinstance(entry, dict): + continue + tool_calls += 1 + tool = entry.get("tool") or "" + if tool and tool not in used_tools: + used_tools.append(tool) + success = bool(entry.get("success", True)) + step = _coerce_step(entry.get("step")) + if step and step not in seen_steps: + seen_steps.add(step) + distinct_steps += 1 + max_step = max(max_step, step) + if not success: + failed_calls += 1 + if entry.get("cached"): + cached_calls += 1 + + key = (tool, _args_key(_entry_arguments(entry))) + if key_counts.get(key, 0): + redundant_calls += 1 + key_counts[key] = key_counts.get(key, 0) + 1 + if key_failed_seen.get(key): + key_retries[key] = key_retries.get(key, 0) + 1 + key_failed_seen[key] = not success + + total = 0 + if total_steps is not None: + try: + total = int(total_steps) + except (TypeError, ValueError): + total = 0 + total = total if total > 0 else 0 + + return _ToolLogMetrics( + tool_calls=tool_calls, + used_tools=used_tools, + redundant_calls=redundant_calls, + cached_calls=cached_calls, + failed_calls=failed_calls, + retries=sum(key_retries.values()), + distinct_steps=max(distinct_steps, total), + max_step=max(max_step, total), + ) + + def compute_trajectory_metrics( log: List[Dict[str, Any]], golden: GoldenSample, @@ -165,10 +258,8 @@ def compute_trajectory_metrics( non-positive ``allowed_max_steps`` is reported with the validator's wording (and the budget assertion stays disabled). """ - used_tools: List[str] = [] - key_counts: Dict[tuple, int] = {} - key_failed_seen: Dict[tuple, bool] = {} - key_retries: Dict[tuple, int] = {} + log_metrics = _compute_tool_log_metrics(log, total_steps=total_steps) + used_tools = log_metrics.used_tools # Extract the expected tool list before scanning entries. Malformed # elements are not silently dropped: they are reported as a violation # below (mirroring validate_golden_sample, which rejects them at load @@ -190,43 +281,12 @@ def compute_trajectory_metrics( expected_dupes = len(set(expected)) != len(expected) if expected_dupes: expected = list(dict.fromkeys(expected)) - failed_calls = 0 - cached_calls = 0 - redundant_calls = 0 - distinct_steps = 0 - max_step = 0 - seen_steps: set = set() - - for entry in log: - if not isinstance(entry, dict): - continue - tool = entry.get("tool") or "" - success = bool(entry.get("success", True)) - if tool and tool not in used_tools: - used_tools.append(tool) - step = _coerce_step(entry.get("step")) - if step and step not in seen_steps: - seen_steps.add(step) - distinct_steps += 1 - max_step = max(max_step, step) - if not success: - failed_calls += 1 - if entry.get("cached"): - cached_calls += 1 - - key = (tool, _args_key(_entry_arguments(entry))) - if key_counts.get(key, 0): - redundant_calls += 1 - key_counts[key] = key_counts.get(key, 0) + 1 - # An occurrence is a retry only when the same call already failed - # before it (see module docstring for the precise contract). - if key_failed_seen.get(key): - key_retries[key] = key_retries.get(key, 0) + 1 - # A success clears the failure state: repeats after a recovery count - # as redundant only, not as further retries. - key_failed_seen[key] = not success - - retries = sum(key_retries.values()) + failed_calls = log_metrics.failed_calls + cached_calls = log_metrics.cached_calls + redundant_calls = log_metrics.redundant_calls + retries = log_metrics.retries + distinct_steps = log_metrics.distinct_steps + max_step = log_metrics.max_step violations: List[str] = [] if expected_dupes: @@ -252,18 +312,6 @@ def compute_trajectory_metrics( if optional_tools_used and not optional_allowed: violations.append(f"optional tools used but not allowed: {', '.join(optional_tools_used)}") - # The final answer round consumes a step but produces no tool call, so - # when the caller supplies the run's real total it may exceed the log. - total = 0 - if total_steps is not None: - try: - total = int(total_steps) - except (TypeError, ValueError): - total = 0 - total = total if total > 0 else 0 - distinct_steps = max(distinct_steps, total) - max_step = max(max_step, total) - limit = golden.allowed_max_steps if isinstance(limit, bool) or not isinstance(limit, int): violations.append("allowed_max_steps must be an integer") @@ -325,6 +373,175 @@ def format_text_report(m: TrajectoryMetrics) -> str: ) +def compute_stage_trajectory_metrics( + trajectories: List[Dict[str, Any]], + golden: GoldenSample, +) -> StageTrajectoryMetrics: + """Normalize stage-local steps and score a multi-agent trajectory. + + The runtime deliberately supplies one snapshot per observed stage. This + function keeps that list order (the specialist scheduler already restores + selected-agent order after concurrent execution), and only derives + cumulative steps from each stage's local ``total_steps``. Missing + expected stages therefore remain missing instead of being inferred from + tool-log gaps. + """ + violations: List[str] = [] + if not isinstance(trajectories, list): + violations.append("stage_trajectories must be a list") + trajectories = [] + + expected_raw = getattr(golden, "expected_stages", []) + if isinstance(expected_raw, list): + expected = [name for name in expected_raw if isinstance(name, str) and name.strip()] + if len(expected) != len(expected_raw): + violations.append("expected_stages must contain only non-empty strings") + if len(set(expected)) != len(expected): + violations.append("expected_stages must not contain duplicate names") + expected = list(dict.fromkeys(expected)) + else: + expected = [] + violations.append("expected_stages must be a list of stage names") + + observed: List[str] = [] + observed_set = set() + completed = failed = skipped = 0 + cumulative_steps = 0 + stage_metrics: List[Dict[str, Any]] = [] + valid_statuses = {"pending", "running", "completed", "failed", "skipped"} + + for index, snapshot in enumerate(trajectories): + if not isinstance(snapshot, dict): + violations.append(f"stage snapshot #{index} must be an object") + continue + + stage_name = snapshot.get("stage_name", "") + if not isinstance(stage_name, str) or not stage_name.strip(): + violations.append(f"stage snapshot #{index} stage_name must be a non-empty string") + stage_name = str(stage_name or "") + else: + stage_name = stage_name.strip() + if stage_name in observed_set: + violations.append(f"duplicate stage snapshot: {stage_name}") + else: + observed.append(stage_name) + observed_set.add(stage_name) + + status = snapshot.get("status", "") + status = getattr(status, "value", status) + if not isinstance(status, str) or status not in valid_statuses: + violations.append(f"stage snapshot #{index} has invalid status") + status = str(status or "") + + raw_steps = snapshot.get("total_steps", 0) + if isinstance(raw_steps, bool) or not isinstance(raw_steps, int) or raw_steps < 0: + violations.append(f"stage snapshot #{index} total_steps must be a non-negative integer") + raw_steps = 0 + local_steps = max(raw_steps, 0) + + raw_log = snapshot.get("tool_calls_log", []) + if not isinstance(raw_log, list): + violations.append(f"stage snapshot #{index} tool_calls_log must be a list") + raw_log = [] + log_steps = max( + (_coerce_step(entry.get("step")) for entry in raw_log if isinstance(entry, dict)), + default=0, + ) + local_steps = max(local_steps, log_steps) + + failure_reason = snapshot.get("failure_reason") + failure_reason = getattr(failure_reason, "value", failure_reason) + if status == "completed": + completed += 1 + elif status == "failed": + failed += 1 + elif status == "skipped": + skipped += 1 + + cumulative_start = cumulative_steps + 1 if local_steps else None + cumulative_steps += local_steps + tool_metrics = _compute_tool_log_metrics(raw_log, total_steps=local_steps) + stage_metrics.append( + { + "stage_name": stage_name, + "status": status, + "failure_reason": failure_reason, + "local_steps": local_steps, + "cumulative_start_step": cumulative_start, + "cumulative_end_step": cumulative_steps, + "tool_metrics": { + "tool_calls": tool_metrics.tool_calls, + "tools_used": tool_metrics.used_tools, + "redundant_calls": tool_metrics.redundant_calls, + "cached_calls": tool_metrics.cached_calls, + "failed_calls": tool_metrics.failed_calls, + "retries": tool_metrics.retries, + }, + } + ) + + missing = [name for name in expected if name not in observed_set] + unexpected = [name for name in observed if expected and name not in expected] + expected_stage_hit_rate = ( + (len(expected) - len(missing)) / len(expected) if expected else None + ) + if expected and missing: + violations.append(f"missing expected stages: {', '.join(missing)}") + if unexpected: + violations.append(f"unexpected stages: {', '.join(unexpected)}") + + return StageTrajectoryMetrics( + expected_stage_hit_rate=expected_stage_hit_rate, + expected_total=len(expected), + missing_expected_stages=missing, + unexpected_stages=unexpected, + observed_stages=observed, + completed_stages=completed, + failed_stages=failed, + skipped_stages=skipped, + cumulative_steps=cumulative_steps, + stage_metrics=stage_metrics, + violations=violations, + ) + + +def format_stage_text_report(m: StageTrajectoryMetrics) -> str: + """Render the stage portion of a multi-agent trajectory report.""" + if m.expected_total: + hit = f"{m.expected_stage_hit_rate * 100:.1f}%" + expected = f"{m.expected_total - len(m.missing_expected_stages)}/{m.expected_total} ({hit})" + else: + expected = "未配置期望阶段" + missing = ", ".join(m.missing_expected_stages) if m.missing_expected_stages else "无" + violations = "; ".join(m.violations) if m.violations else "无" + lines = [ + "--------------------------------------------", + "Multi-Agent 阶段轨迹", + "--------------------------------------------", + f"- 期望阶段命中: {expected}", + f"- 观测阶段: {', '.join(m.observed_stages) if m.observed_stages else '无'}", + f"- 缺失期望阶段: {missing}", + f"- 阶段状态: 已完成 {m.completed_stages} | 失败 {m.failed_stages} | 跳过 {m.skipped_stages}", + f"- 累计步数: {m.cumulative_steps}", + f"- 阶段违规项: {violations}", + ] + for stage in m.stage_metrics: + start = stage.get("cumulative_start_step") + end = stage.get("cumulative_end_step", 0) + cumulative = f"{start}-{end}" if start is not None else "无" + reason = stage.get("failure_reason") or "无" + tool_metrics = stage.get("tool_metrics") or {} + lines.append( + f"- 阶段 {stage.get('stage_name') or '(未命名)'}: " + f"状态={stage.get('status') or 'unknown'} | " + f"局部步数={stage.get('local_steps', 0)} | 累计步数={cumulative} | " + f"失败原因={reason} | 工具调用={tool_metrics.get('tool_calls', 0)} | " + f"工具失败={tool_metrics.get('failed_calls', 0)} | " + f"重试={tool_metrics.get('retries', 0)}" + ) + return "\n".join(lines) + "\n" + + def load_golden_samples( path: Optional[str] = None, known_tool_names: Optional[Iterable[str]] = None, @@ -418,4 +635,10 @@ def validate_golden_sample( issues.append("allowed_max_steps must be >= 1") if not isinstance(sample.allow_optional_tools, bool): issues.append("allow_optional_tools must be a boolean") + if not isinstance(sample.expected_stages, list): + issues.append("expected_stages must be a list of stage names") + elif any(not isinstance(name, str) or not name.strip() for name in sample.expected_stages): + issues.append("expected_stages must contain only non-empty strings") + elif len(set(sample.expected_stages)) != len(sample.expected_stages): + issues.append("expected_stages must not contain duplicate names") return issues diff --git a/evals/agent_trajectory/run_eval.py b/evals/agent_trajectory/run_eval.py index 28dd9cfda6f..22d19465be8 100644 --- a/evals/agent_trajectory/run_eval.py +++ b/evals/agent_trajectory/run_eval.py @@ -12,10 +12,9 @@ they never fail the process. Exit codes: 0 = ran (violations included), 1 = load (golden / tool registry) / build / run failure, 2 = usage error. -The entry supports the single-agent runner only. When ``AGENT_ARCH=multi`` -the factory returns the orchestrator whose trajectories use per-stage local -step numbers, which breaks the single-runner metric contract, so the entry -rejects that arch up front with exit code 1. Golden samples are validated +The entry supports both single-agent and multi-agent results. Multi-agent +runs retain the existing flattened tool metrics and add a stage-aware report +section based on explicit orchestrator snapshots. Golden samples are validated against the real tool registry before running, so misspelled or stale ``expected_tools`` fail as invalid samples instead of scoring as low hit rate. @@ -41,8 +40,11 @@ from evals.agent_trajectory.metrics import ( GoldenSample, + StageTrajectoryMetrics, TrajectoryMetrics, + compute_stage_trajectory_metrics, compute_trajectory_metrics, + format_stage_text_report, format_text_report, load_golden_samples, ) @@ -59,6 +61,19 @@ def _build_report(sample: GoldenSample, metrics: TrajectoryMetrics) -> Dict[str, } +def _build_multi_report( + sample: GoldenSample, + metrics: TrajectoryMetrics, + stage_metrics: StageTrajectoryMetrics, +) -> Dict[str, Any]: + """Extend the historical report only when stage snapshots are present.""" + report = _build_report(sample, metrics) + report["run_status"] = "completed" + report["stage_metrics"] = asdict(stage_metrics) + report["violations"] = list(dict.fromkeys(metrics.violations + stage_metrics.violations)) + return report + + def _write_json(path: Optional[Path], payload: Any) -> None: """Write ``payload`` as indented UTF-8 JSON (trailing newline).""" if path is None: @@ -69,24 +84,12 @@ def _write_json(path: Optional[Path], payload: Any) -> None: _KNOWN_TOOL_NAMES: Optional[set] = None -def _check_agent_arch() -> None: - """Reject multi-agent arch up front (mirrors the factory's own decision). - - ``src.agent.factory.build_agent_executor`` returns the orchestrator when - ``config.agent_arch == "multi"``; its trajectories concatenate per-stage - logs with local step numbering and set ``total_steps`` to the stage count, - which the single-runner metric contract cannot interpret. Fail fast - instead of scoring a distorted trajectory. - """ +def _check_agent_arch() -> str: + """Read the configured architecture without rejecting multi-agent runs.""" from src.config import get_config arch = getattr(get_config(), "agent_arch", "single") - if arch == "multi": - raise RuntimeError( - "AGENT_ARCH=multi is not supported by this minimal eval: " - "orchestrator trajectories use per-stage local step numbers, " - "which break the single-runner metric contract" - ) + return str(arch or "single") def _known_tool_names(): @@ -117,6 +120,41 @@ def _build_executor(): return build_agent_executor() +def _evaluate_sample(executor, sample: GoldenSample): + """Run and score a sample, returning the metrics and its report payload.""" + context: Optional[Dict[str, Any]] = None + if sample.stock_code: + context = {"stock_code": sample.stock_code} + result = executor.run(sample.task_description, context=context) + run_failed = getattr(result, "success", None) is False + error = getattr(result, "error", None) + trajectories = getattr(result, "stage_trajectories", None) or [] + # Preserve historical behavior for single-agent/legacy results. A failed + # Multi-Agent result has an explicit stage trace that must be scored and + # written before the CLI returns its non-zero exit status. + if run_failed and not trajectories: + raise RuntimeError(f"agent run failed (success=false): {error or 'no error detail'}") + + log = getattr(result, "tool_calls_log", None) or [] + stage_metrics = None + if trajectories: + stage_metrics = compute_stage_trajectory_metrics(trajectories, sample) + # The orchestrator's public total_steps retains its historical meaning + # (number of stages). For trajectory scoring, the snapshots carry the + # authoritative per-stage loop counts and must be summed once. + total_steps = stage_metrics.cumulative_steps + else: + total_steps = getattr(result, "total_steps", None) + metrics = compute_trajectory_metrics(log, sample, total_steps=total_steps) + if trajectories: + report = _build_multi_report(sample, metrics, stage_metrics) + if run_failed: + report["run_status"] = "failed" + run_error = (error or "agent run failed (success=false)") if run_failed else None + return metrics, stage_metrics, report, run_error + return metrics, None, _build_report(sample, metrics), None + + def run_sample(executor, sample: GoldenSample, *, json_out: Optional[Path] = None) -> TrajectoryMetrics: """Run one golden sample against a duck-typed agent executor and score it. @@ -124,25 +162,19 @@ def run_sample(executor, sample: GoldenSample, *, json_out: Optional[Path] = Non ``result`` carries ``tool_calls_log`` (and optionally ``total_steps``) — the same shape as ``src.agent.executor.AgentResult``. The production executor is built lazily by :func:`_build_executor`; tests may pass a - stub. A result carrying an explicit ``success=False`` is a run failure - (the executor reported a provider / timeout / budget error) and raises - ``RuntimeError`` before any scoring; duck-typed results without a - ``success`` attribute are treated as successful. The text summary is - always printed to stdout; ``json_out`` additionally writes the - structured report for this sample. + stub. A result carrying ``success=False`` and no stage snapshots raises as + before. When a failed Multi-Agent result includes stage snapshots, this + function prints and writes the diagnostic report first, then raises + ``RuntimeError`` so the CLI still exits with code 1. Duck-typed results + without a ``success`` attribute are treated as successful. """ - context: Optional[Dict[str, Any]] = None - if sample.stock_code: - context = {"stock_code": sample.stock_code} - result = executor.run(sample.task_description, context=context) - if getattr(result, "success", None) is False: - error = getattr(result, "error", None) - raise RuntimeError(f"agent run failed (success=false): {error or 'no error detail'}") - log = getattr(result, "tool_calls_log", None) or [] - total_steps = getattr(result, "total_steps", None) - metrics = compute_trajectory_metrics(log, sample, total_steps=total_steps) + metrics, stage_metrics, report, run_error = _evaluate_sample(executor, sample) print(format_text_report(metrics)) - _write_json(json_out, _build_report(sample, metrics)) + if stage_metrics is not None: + print(format_stage_text_report(stage_metrics)) + _write_json(json_out, report) + if run_error: + raise RuntimeError(f"agent run failed (success=false): {run_error}") return metrics @@ -193,18 +225,29 @@ def main(argv=None) -> int: return 1 reports: Dict[str, Dict[str, Any]] = {} + failed_multi_run = False for sample in samples: print(f"[eval] sample: {sample.id} | task: {sample.task_description}") try: - metrics = run_sample(executor, sample) + metrics, stage_metrics, report, run_error = _evaluate_sample(executor, sample) + print(format_text_report(metrics)) + if stage_metrics is not None: + print(format_stage_text_report(stage_metrics)) except Exception as exc: print(f"error: sample '{sample.id}' failed: {exc}", file=sys.stderr) return 1 - reports[sample.id] = _build_report(sample, metrics) + reports[sample.id] = report + if run_error: + failed_multi_run = True + print( + f"error: sample '{sample.id}' failed: " + f"agent run failed (success=false): {run_error}", + file=sys.stderr, + ) if args.json_out: _write_json(Path(args.json_out), reports if args.all else reports[args.sample]) - return 0 + return 1 if failed_multi_run else 0 if __name__ == "__main__": diff --git a/src/agent/agents/base_agent.py b/src/agent/agents/base_agent.py index 588826918b7..68b8be35845 100644 --- a/src/agent/agents/base_agent.py +++ b/src/agent/agents/base_agent.py @@ -133,6 +133,9 @@ def run( result.tokens_used = loop_result.total_tokens result.tool_calls_count = len(loop_result.tool_calls_log) + # Keep compatibility with lightweight test doubles and legacy + # adapters that predate RunLoopResult.total_steps. + result.total_steps = getattr(loop_result, "total_steps", 0) result.meta["raw_text"] = loop_result.content result.meta["models_used"] = loop_result.models_used result.meta["tool_calls_log"] = loop_result.tool_calls_log diff --git a/src/agent/executor.py b/src/agent/executor.py index 7e6b1c266d4..d09795a8aae 100644 --- a/src/agent/executor.py +++ b/src/agent/executor.py @@ -59,6 +59,9 @@ class AgentResult: backend: str = "" error_code: Optional[str] = None usage: Optional[Dict[str, Any]] = None + # Optional whitelisted snapshots for multi-agent trajectory evaluation. + # Single-agent callers continue to receive the historical empty list. + stage_trajectories: List[Dict[str, Any]] = field(default_factory=list) # ============================================================ diff --git a/src/agent/orchestrator.py b/src/agent/orchestrator.py index 882832df74f..c0dd06d36f7 100644 --- a/src/agent/orchestrator.py +++ b/src/agent/orchestrator.py @@ -79,6 +79,51 @@ NON_CRITICAL_BASE_STAGES = frozenset({"intel", "risk"}) +def _stage_trajectory_snapshot(result: StageResult) -> Dict[str, Any]: + """Return the small JSON-safe stage trace exposed to the eval boundary. + + ``StageResult.meta`` also contains runtime-only values such as raw model + text. Keep this boundary deliberately whitelisted so the evaluator sees + execution facts without receiving prompts, messages, or arbitrary metadata. + """ + status = getattr(result.status, "value", result.status) + failure_reason = result.failure_reason + if failure_reason is None and result.status == StageStatus.FAILED: + failure_reason = StageFailureReason.STAGE_FAILURE + failure_reason = getattr(failure_reason, "value", failure_reason) + raw_steps = result.total_steps + try: + total_steps = max(0, int(raw_steps or 0)) + except (TypeError, ValueError): + total_steps = 0 + raw_log = result.meta.get("tool_calls_log") or [] + tool_calls_log = [dict(entry) if isinstance(entry, dict) else entry for entry in raw_log] + return { + "stage_name": str(result.stage_name or ""), + "status": str(status), + "total_steps": total_steps, + "tool_calls_log": tool_calls_log, + "failure_reason": str(failure_reason) if failure_reason is not None else None, + "duration_s": result.duration_s, + "tokens_used": result.tokens_used, + "tool_calls_count": result.tool_calls_count, + } + + +def _skipped_stage_trajectory(stage_name: str, reason: StageFailureReason) -> Dict[str, Any]: + """Represent a stage that was not started at a pipeline boundary.""" + return { + "stage_name": str(stage_name or ""), + "status": StageStatus.SKIPPED.value, + "total_steps": 0, + "tool_calls_log": [], + "failure_reason": reason.value, + "duration_s": 0.0, + "tokens_used": 0, + "tool_calls_count": 0, + } + + @dataclass class OrchestratorResult: """Unified result from a multi-agent pipeline run.""" @@ -94,6 +139,7 @@ class OrchestratorResult: error: Optional[str] = None stats: Optional[AgentRunStats] = None runtime_facts: Optional[AgentRuntimeFacts] = None + stage_trajectories: List[Dict[str, Any]] = field(default_factory=list) @dataclass(frozen=True) @@ -182,6 +228,7 @@ def _build_timeout_result( timeout_s: int, ctx: Optional[AgentContext] = None, parse_dashboard: bool = True, + stage_trajectories: Optional[List[Dict[str, Any]]] = None, ) -> OrchestratorResult: """Build a standard timeout result payload.""" stats.total_duration_s = round(elapsed_s, 2) @@ -211,6 +258,7 @@ def _build_timeout_result( total_steps=stats.total_stages, total_tokens=stats.total_tokens, tool_calls_log=all_tool_calls, + stage_trajectories=list(stage_trajectories or []), provider=provider, model=model, runtime_facts=build_agent_runtime_facts(ctx) if ctx is not None else None, @@ -228,6 +276,7 @@ def _build_budget_skip_result( min_stage_budget_s: int, ctx: Optional[AgentContext] = None, parse_dashboard: bool = True, + stage_trajectories: Optional[List[Dict[str, Any]]] = None, ) -> OrchestratorResult: """Build a result for budget-insufficient stage skip (non-timeout semantics).""" stats.total_duration_s = round(elapsed_s, 2) @@ -256,6 +305,7 @@ def _build_budget_skip_result( total_steps=stats.total_stages, total_tokens=stats.total_tokens, tool_calls_log=all_tool_calls, + stage_trajectories=list(stage_trajectories or []), provider=stats.models_used[0] if stats.models_used else "", model=", ".join(stats.models_used), runtime_facts=build_agent_runtime_facts(ctx) if ctx is not None else None, @@ -370,6 +420,7 @@ def run(self, task: str, context: Optional[Dict[str, Any]] = None) -> "AgentResu provider=orch_result.provider, model=orch_result.model, error=orch_result.error, + stage_trajectories=orch_result.stage_trajectories, runtime_facts=orch_result.runtime_facts, ) @@ -469,6 +520,7 @@ def execute_turn( provider=orch_result.provider, model=orch_result.model, error=orch_result.error, + stage_trajectories=orch_result.stage_trajectories, runtime_facts=orch_result.runtime_facts, ) @@ -485,6 +537,7 @@ def _execute_pipeline( """Run the agent pipeline according to ``self.mode``.""" stats = AgentRunStats() all_tool_calls: List[Dict[str, Any]] = [] + stage_trajectories: List[Dict[str, Any]] = [] models_used: List[str] = [] t0 = time.time() timeout_s = self._get_timeout_seconds() @@ -535,6 +588,9 @@ def _execute_pipeline( )) if ctx is not None: self._apply_partition_fallback(ctx) + stage_trajectories.append( + _skipped_stage_trajectory(agent.agent_name, StageFailureReason.TIMEOUT) + ) return self._build_timeout_result( stats, all_tool_calls, @@ -543,6 +599,7 @@ def _execute_pipeline( timeout_s, ctx=ctx, parse_dashboard=parse_dashboard, + stage_trajectories=stage_trajectories, ) if budget_guard_triggered: @@ -574,6 +631,9 @@ def _execute_pipeline( )) if ctx is not None: self._apply_partition_fallback(ctx) + stage_trajectories.append( + _skipped_stage_trajectory(agent.agent_name, StageFailureReason.BUDGET_SKIP) + ) return self._build_budget_skip_result( stats, all_tool_calls, @@ -585,6 +645,7 @@ def _execute_pipeline( stage_min_budget_s, ctx=ctx, parse_dashboard=parse_dashboard, + stage_trajectories=stage_trajectories, ) if ( @@ -604,6 +665,7 @@ def _execute_pipeline( ) for stage_result in batch.stage_results: stats.record_stage(stage_result) + stage_trajectories.append(_stage_trajectory_snapshot(stage_result)) all_tool_calls.extend( tc for tc in (stage_result.meta.get("tool_calls_log") or []) ) @@ -651,6 +713,7 @@ def _execute_pipeline( timeout_seconds=remaining_timeout_s, ) stats.record_stage(result) + stage_trajectories.append(_stage_trajectory_snapshot(result)) all_tool_calls.extend( tc for tc in (result.meta.get("tool_calls_log") or []) ) @@ -681,8 +744,10 @@ def _execute_pipeline( success=False, error=f"Stage '{agent.agent_name}' failed: {result.error}", stats=stats, + total_steps=stats.total_stages, total_tokens=stats.total_tokens, tool_calls_log=all_tool_calls, + stage_trajectories=stage_trajectories, runtime_facts=build_agent_runtime_facts(ctx), ) else: @@ -723,6 +788,7 @@ def _execute_pipeline( timeout_s, ctx=ctx, parse_dashboard=parse_dashboard, + stage_trajectories=stage_trajectories, ) index += 1 @@ -749,6 +815,7 @@ def _execute_pipeline( model=model_str, error="Failed to parse dashboard JSON from agent response", stats=stats, + stage_trajectories=stage_trajectories, runtime_facts=build_agent_runtime_facts(ctx), ) @@ -762,6 +829,7 @@ def _execute_pipeline( provider=provider, model=model_str, stats=stats, + stage_trajectories=stage_trajectories, runtime_facts=build_agent_runtime_facts(ctx), ) diff --git a/src/agent/protocols.py b/src/agent/protocols.py index c5d7c786963..26af40eaba0 100644 --- a/src/agent/protocols.py +++ b/src/agent/protocols.py @@ -310,6 +310,11 @@ class StageResult: tokens_used: int = 0 tool_calls_count: int = 0 meta: Dict[str, Any] = field(default_factory=dict) + # Number of local agent-loop rounds consumed by this stage. This is kept + # separate from the orchestrator's stage count so trajectory evaluators + # can normalize repeated local step numbers without changing runtime + # semantics. + total_steps: int = 0 @property def success(self) -> bool: diff --git a/tests/agent/test_runtime_facts.py b/tests/agent/test_runtime_facts.py index 2df9a2898aa..de4958d5224 100644 --- a/tests/agent/test_runtime_facts.py +++ b/tests/agent/test_runtime_facts.py @@ -611,6 +611,7 @@ def test_runner_failure_sources_propagate_through_base_agent(): assert stage_result.status == StageStatus.FAILED assert stage_result.failure_reason == expected_reason + assert stage_result.total_steps == loop_result.total_steps with patch("src.agent.agents.base_agent.run_agent_loop", side_effect=RuntimeError("opaque")): stage_result = agent.run(AgentContext()) diff --git a/tests/test_agent_trajectory_metrics.py b/tests/test_agent_trajectory_metrics.py index 9e1a7a31c77..0fd781eae6e 100644 --- a/tests/test_agent_trajectory_metrics.py +++ b/tests/test_agent_trajectory_metrics.py @@ -14,8 +14,10 @@ from evals.agent_trajectory.metrics import ( GoldenSample, + StageTrajectoryMetrics, TrajectoryMetrics, _args_key, + compute_stage_trajectory_metrics, compute_trajectory_metrics, format_text_report, load_golden_samples, @@ -428,6 +430,81 @@ def test_violations_rendered(self): text = format_text_report(_metrics(violations=["trajectory reached allowed_max_steps (5)"])) assert "违规项: trajectory reached allowed_max_steps (5)" in text + +class TestStageTrajectoryMetrics: + def test_local_steps_are_normalized_in_stable_order(self): + golden = _golden(expected_stages=["technical", "intel", "decision"]) + metrics = compute_stage_trajectory_metrics( + [ + { + "stage_name": "technical", + "status": "completed", + "total_steps": 2, + "tool_calls_log": [_entry(step=1)], + }, + { + "stage_name": "intel", + "status": "failed", + "failure_reason": "stage_failure", + "total_steps": 1, + "tool_calls_log": [], + }, + { + "stage_name": "decision", + "status": "skipped", + "failure_reason": "budget_skip", + "total_steps": 0, + "tool_calls_log": [], + }, + ], + golden, + ) + + assert isinstance(metrics, StageTrajectoryMetrics) + assert metrics.expected_stage_hit_rate == 1.0 + assert metrics.observed_stages == ["technical", "intel", "decision"] + assert metrics.completed_stages == 1 + assert metrics.failed_stages == 1 + assert metrics.skipped_stages == 1 + assert metrics.cumulative_steps == 3 + assert [item["local_steps"] for item in metrics.stage_metrics] == [2, 1, 0] + assert metrics.stage_metrics[0]["cumulative_end_step"] == 2 + assert metrics.stage_metrics[1]["cumulative_start_step"] == 3 + + def test_missing_and_extra_stages_are_reported(self): + golden = _golden(expected_stages=["technical", "decision"]) + metrics = compute_stage_trajectory_metrics( + [ + { + "stage_name": "technical", + "status": "completed", + "total_steps": 1, + "tool_calls_log": [], + }, + { + "stage_name": "risk", + "status": "completed", + "total_steps": 1, + "tool_calls_log": [], + }, + ], + golden, + ) + + assert metrics.missing_expected_stages == ["decision"] + assert metrics.unexpected_stages == ["risk"] + assert any("missing expected stages" in item for item in metrics.violations) + assert any("unexpected stages" in item for item in metrics.violations) + + def test_malformed_snapshot_is_reported_without_raising(self): + metrics = compute_stage_trajectory_metrics( + [{"stage_name": "technical", "status": "unknown", "total_steps": -1, "tool_calls_log": {}}], + _golden(expected_stages=["technical"]), + ) + + assert metrics.stage_metrics[0]["local_steps"] == 0 + assert len(metrics.violations) >= 3 + def test_deterministic(self): m = _metrics(redundant_calls=2, retries=1, max_steps_touched=True) assert format_text_report(m) == format_text_report(m) diff --git a/tests/test_agent_trajectory_run_eval.py b/tests/test_agent_trajectory_run_eval.py index a9fe9beff0e..833962fd40f 100644 --- a/tests/test_agent_trajectory_run_eval.py +++ b/tests/test_agent_trajectory_run_eval.py @@ -5,14 +5,16 @@ duck-typed stub, and the three checked-in fixtures provide real-shaped ``tool_calls_log`` payloads covering the positive path, the negative path (missing expected tool + cached failure + max_steps) and the retry path. -The two runtime-seam guards (multi-arch rejection and golden validation +The two runtime-seam guards (multi-arch acceptance and golden validation against the real tool registry) are exercised via monkeypatched config / registry access plus one lazy real-registry check. """ import json +import sys from pathlib import Path from types import SimpleNamespace +from unittest.mock import MagicMock, patch import pytest @@ -22,7 +24,7 @@ FIXTURES_DIR = Path(__file__).resolve().parent / "fixtures" / "agent_trajectory" -def _stub_executor(log, total_steps=None): +def _stub_executor(log, total_steps=None, stage_trajectories=None): """Duck-typed executor recording its run calls (no src/ import).""" class _Stub: @@ -31,7 +33,11 @@ def __init__(self): def run(self, task, context=None): self.calls.append((task, context)) - return SimpleNamespace(tool_calls_log=list(log), total_steps=total_steps) + return SimpleNamespace( + tool_calls_log=list(log), + total_steps=total_steps, + stage_trajectories=list(stage_trajectories or []), + ) return _Stub() @@ -168,8 +174,8 @@ def test_fail_success_success_counts_one_retry(self): # 3.5 run failure: results carrying an explicit success=False # --------------------------------------------------------------------------- class TestRunFailure: - def test_unsuccessful_result_raises_before_scoring(self, capsys): - # Owner repro: a real AgentResult with success=False must not be scored. + def test_unsuccessful_single_agent_result_raises_without_report(self, capsys): + # Single-agent failure behavior stays unchanged when no stage trace exists. executor = _result_executor(SimpleNamespace(success=False, error="boom", tool_calls_log=[], total_steps=0)) with pytest.raises(RuntimeError, match="boom"): run_eval.run_sample(executor, _goldens()["600519_technical"]) @@ -199,17 +205,160 @@ def test_success_none_is_tolerated(self): m = run_eval.run_sample(_result_executor(result), _goldens()["600519_technical"]) assert m.expected_hit_rate == 1.0 + def test_failed_multi_agent_result_writes_stage_report_before_raising(self, tmp_path, capsys): + stage_log = [{"step": 1, "tool": "get_realtime_quote", "success": False}] + result = SimpleNamespace( + success=False, + error="Stage 'technical' failed: provider timeout", + tool_calls_log=stage_log, + total_steps=1, + stage_trajectories=[ + { + "stage_name": "technical", + "status": "failed", + "failure_reason": "timeout", + "total_steps": 3, + "tool_calls_log": stage_log, + } + ], + ) + sample = GoldenSample( + id="failed_multi", + task_description="multi-agent failure", + expected_tools=["get_realtime_quote"], + expected_stages=["technical", "decision"], + ) + out = tmp_path / "failed-multi.json" + + with pytest.raises(RuntimeError, match="provider timeout"): + run_eval.run_sample(_result_executor(result), sample, json_out=out) + + report = json.loads(out.read_text(encoding="utf-8")) + stage_metrics = report["stage_metrics"] + assert report["run_status"] == "failed" + assert stage_metrics["failed_stages"] == 1 + assert stage_metrics["missing_expected_stages"] == ["decision"] + assert stage_metrics["cumulative_steps"] == 3 + assert stage_metrics["stage_metrics"][0]["failure_reason"] == "timeout" + output = capsys.readouterr().out + assert "阶段 technical: 状态=failed" in output + assert "局部步数=3" in output + assert "缺失期望阶段: decision" in output + assert "失败原因=timeout" in output + + def test_orchestrator_critical_failure_reaches_stage_report(self, tmp_path, capsys): + try: + import litellm # noqa: F401 + except ModuleNotFoundError: + sys.modules["litellm"] = MagicMock() + + from src.agent.orchestrator import AgentOrchestrator + from src.agent.protocols import StageFailureReason, StageResult, StageStatus + + tool_log = [{"step": 1, "tool": "get_realtime_quote", "success": False}] + technical = MagicMock(agent_name="technical") + technical.run.return_value = StageResult( + stage_name="technical", + status=StageStatus.FAILED, + failure_reason=StageFailureReason.TIMEOUT, + total_steps=3, + meta={"tool_calls_log": tool_log}, + ) + orchestrator = AgentOrchestrator(tool_registry=MagicMock(), llm_adapter=MagicMock()) + sample = GoldenSample( + id="orchestrator_failure", + task_description="critical stage failure", + expected_tools=["get_realtime_quote"], + expected_stages=["technical", "decision"], + ) + report_path = tmp_path / "orchestrator-failure.json" + + with patch.object(orchestrator, "_build_agent_chain", return_value=[technical]): + result = orchestrator.run(sample.task_description) + + assert result.success is False + assert result.stage_trajectories[0]["status"] == "failed" + assert result.stage_trajectories[0]["failure_reason"] == "timeout" + with pytest.raises(RuntimeError, match="Stage 'technical' failed"): + run_eval.run_sample(_result_executor(result), sample, json_out=report_path) + + report = json.loads(report_path.read_text(encoding="utf-8")) + assert report["run_status"] == "failed" + assert report["stage_metrics"]["failed_stages"] == 1 + assert report["stage_metrics"]["missing_expected_stages"] == ["decision"] + assert report["stage_metrics"]["cumulative_steps"] == 3 + output = capsys.readouterr().out + assert "阶段 technical: 状态=failed" in output + assert "失败原因=timeout" in output + + def test_orchestrator_stage_loop_totals_drive_global_budget_metrics(self, tmp_path, capsys): + try: + import litellm # noqa: F401 + except ModuleNotFoundError: + sys.modules["litellm"] = MagicMock() + + from src.agent.orchestrator import AgentOrchestrator + from src.agent.protocols import StageResult, StageStatus + + quote_log = [{"step": 1, "tool": "quote", "success": True}] + news_log = [{"step": 1, "tool": "news", "success": True}] + technical = MagicMock(agent_name="technical") + technical.run.return_value = StageResult( + stage_name="technical", + status=StageStatus.COMPLETED, + total_steps=3, + meta={"tool_calls_log": quote_log}, + ) + intel = MagicMock(agent_name="intel") + intel.run.return_value = StageResult( + stage_name="intel", + status=StageStatus.COMPLETED, + total_steps=3, + meta={"tool_calls_log": news_log}, + ) + orchestrator = AgentOrchestrator(tool_registry=MagicMock(), llm_adapter=MagicMock()) + with ( + patch.object(orchestrator, "_build_agent_chain", return_value=[technical, intel]), + patch.object( + orchestrator, + "_resolve_final_output", + return_value=({"ok": True}, "final report"), + ), + ): + result = orchestrator.run("analyze one stock") + + # Keep the runtime's established stage-count contract; the evaluator + # must derive loop totals from the explicit stage snapshots instead. + assert result.total_steps == 2 + assert [item["total_steps"] for item in result.stage_trajectories] == [3, 3] + sample = GoldenSample( + id="multi_aggregate_steps", + task_description="analyze one stock", + expected_tools=["quote", "news"], + allowed_max_steps=5, + expected_stages=["technical", "intel"], + ) + report_path = tmp_path / "aggregate-steps.json" + + run_eval.run_sample(_result_executor(result), sample, json_out=report_path) + + report = json.loads(report_path.read_text(encoding="utf-8")) + assert report["stage_metrics"]["cumulative_steps"] == 6 + assert report["metrics"]["distinct_steps"] == 6 + assert report["metrics"]["max_steps_touched"] is True + assert report["violations"] == ["trajectory reached allowed_max_steps (5)"] + assert "消耗步数: 6 (触碰 max_steps: 是)" in capsys.readouterr().out + # --------------------------------------------------------------------------- # 4. runtime-seam guards: multi-arch rejection + golden registry validation # --------------------------------------------------------------------------- class TestArchGuard: - def test_multi_arch_raises(self, monkeypatch): + def test_multi_arch_is_allowed(self, monkeypatch): import src.config monkeypatch.setattr(src.config, "get_config", lambda: SimpleNamespace(agent_arch="multi")) - with pytest.raises(RuntimeError, match="multi"): - run_eval._check_agent_arch() + assert run_eval._check_agent_arch() == "multi" def test_single_arch_passes(self, monkeypatch): import src.config @@ -293,13 +442,173 @@ def _boom(): assert run_eval.main(["--sample", "600519_technical"]) == 1 assert "failed to build agent executor" in capsys.readouterr().err - def test_multi_arch_build_rejection_exit_one(self, monkeypatch, capsys): - def _boom(): - raise RuntimeError("AGENT_ARCH=multi is not supported by this minimal eval") + def test_multi_arch_result_emits_stage_report(self, tmp_path, capsys): + log, total_steps = _fixture("positive_600519_technical") + result = SimpleNamespace( + success=True, + tool_calls_log=list(log), + total_steps=total_steps, + stage_trajectories=[ + { + "stage_name": "technical", + "status": "completed", + "total_steps": 2, + "tool_calls_log": list(log), + }, + { + "stage_name": "decision", + "status": "skipped", + "total_steps": 0, + "tool_calls_log": [], + "failure_reason": "budget_skip", + }, + ], + ) + out = tmp_path / "multi.json" + run_eval.run_sample( + _result_executor(result), + GoldenSample( + id="multi", + task_description="multi task", + expected_tools=["get_realtime_quote", "get_daily_history", "analyze_trend"], + expected_stages=["technical", "decision"], + ), + json_out=out, + ) - monkeypatch.setattr(run_eval, "_build_executor", _boom) - assert run_eval.main(["--sample", "600519_technical"]) == 1 - assert "multi" in capsys.readouterr().err + report = json.loads(out.read_text(encoding="utf-8")) + assert report["stage_metrics"]["expected_stage_hit_rate"] == 1.0 + assert report["stage_metrics"]["skipped_stages"] == 1 + assert "Multi-Agent 阶段轨迹" in capsys.readouterr().out + + def test_multi_agent_tool_metrics_are_local_while_golden_scoring_is_global(self, tmp_path, capsys): + quote_failed = { + "step": 1, + "tool": "quote", + "arguments": {"symbol": "600519"}, + "success": False, + "cached": False, + } + quote_retry = { + "step": 2, + "tool": "quote", + "arguments": {"symbol": "600519"}, + "success": True, + "cached": False, + } + news_call = { + "step": 1, + "tool": "news", + "arguments": {"symbol": "600519"}, + "success": True, + "cached": True, + } + result = SimpleNamespace( + success=True, + tool_calls_log=[quote_failed, quote_retry, news_call], + total_steps=6, + stage_trajectories=[ + { + "stage_name": "technical", + "status": "completed", + "total_steps": 3, + "tool_calls_log": [quote_failed, quote_retry], + }, + { + "stage_name": "intel", + "status": "completed", + "total_steps": 3, + "tool_calls_log": [news_call], + }, + ], + ) + sample = GoldenSample( + id="multi_stage_tool_expectations", + task_description="Use quote in technical and news in intel", + expected_tools=["quote", "news"], + allowed_max_steps=3, + allow_optional_tools=False, + expected_stages=["technical", "intel"], + ) + out = tmp_path / "multi-stage-tools.json" + + run_eval.run_sample(_result_executor(result), sample, json_out=out) + + report = json.loads(out.read_text(encoding="utf-8")) + assert report["metrics"]["expected_hit_rate"] == 1.0 + assert report["metrics"]["missing_expected"] == [] + assert report["metrics"]["optional_tools_used"] == [] + assert report["metrics"]["max_steps_touched"] is True + assert report["violations"] == ["trajectory reached allowed_max_steps (3)"] + + stages = report["stage_metrics"]["stage_metrics"] + technical_tools = stages[0]["tool_metrics"] + intel_tools = stages[1]["tool_metrics"] + assert technical_tools == { + "tool_calls": 2, + "tools_used": ["quote"], + "redundant_calls": 1, + "cached_calls": 0, + "failed_calls": 1, + "retries": 1, + } + assert intel_tools == { + "tool_calls": 1, + "tools_used": ["news"], + "redundant_calls": 0, + "cached_calls": 1, + "failed_calls": 0, + "retries": 0, + } + assert report["stage_metrics"]["violations"] == [] + output = capsys.readouterr().out + assert "工具调用=2 | 工具失败=1 | 重试=1" in output + assert "工具调用=1 | 工具失败=0 | 重试=0" in output + + def test_failed_multi_agent_cli_writes_json_and_returns_one(self, tmp_path, monkeypatch, capsys): + golden_path = tmp_path / "golden.json" + golden_path.write_text( + json.dumps( + [ + { + "id": "failed_multi", + "task_description": "multi-agent failure", + "stock_code": "", + "expected_tools": ["get_realtime_quote"], + "expected_stages": ["technical", "decision"], + } + ] + ), + encoding="utf-8", + ) + stage_log = [{"step": 1, "tool": "get_realtime_quote", "success": False}] + failed_result = SimpleNamespace( + success=False, + error="technical provider timeout", + tool_calls_log=stage_log, + total_steps=1, + stage_trajectories=[ + { + "stage_name": "technical", + "status": "failed", + "failure_reason": "timeout", + "total_steps": 2, + "tool_calls_log": stage_log, + } + ], + ) + out = tmp_path / "cli-report.json" + monkeypatch.setattr(run_eval, "_known_tool_names", lambda: {"get_realtime_quote"}) + monkeypatch.setattr(run_eval, "_build_executor", lambda: _result_executor(failed_result)) + + assert run_eval.main( + ["--sample", "failed_multi", "--golden-path", str(golden_path), "--json-out", str(out)] + ) == 1 + + report = json.loads(out.read_text(encoding="utf-8")) + assert report["run_status"] == "failed" + assert report["stage_metrics"]["missing_expected_stages"] == ["decision"] + assert "状态=failed" in capsys.readouterr().out def test_run_failure_exit_one(self, monkeypatch, capsys): class _Exploding: diff --git a/tests/test_multi_agent.py b/tests/test_multi_agent.py index 3816c0dff5e..1a8d6d1c902 100644 --- a/tests/test_multi_agent.py +++ b/tests/test_multi_agent.py @@ -42,6 +42,7 @@ strategy_opinion_from_agent_opinion, StrategySynthesizer, ) +from src.agent.skills.scheduler import SkillBatchResult from src.agent.skills.aggregator import SkillAggregator from src.agent.stock_scope import StockScope, resolve_stock_scope from src.config import AGENT_MAX_STEPS_DEFAULT, Config @@ -1211,10 +1212,21 @@ def _make_orchestrator(config=None): ) @staticmethod - def _stage_result(name, status=StageStatus.COMPLETED, error=None, raw_text="ok"): + def _stage_result( + name, + status=StageStatus.COMPLETED, + error=None, + raw_text="ok", + total_steps=0, + tool_calls_log=None, + failure_reason=None, + ): result = StageResult(stage_name=name, status=status, error=error) + result.total_steps = total_steps + result.failure_reason = failure_reason result.meta["raw_text"] = raw_text result.meta["models_used"] = ["test/model"] + result.meta["tool_calls_log"] = list(tool_calls_log or []) return result @staticmethod @@ -1330,6 +1342,64 @@ def test_execute_pipeline_stops_on_critical_failure(self): self.assertIn("technical", result.error) self.assertEqual(result.total_tokens, 0) + def test_execute_pipeline_collects_whitelisted_stage_trajectories(self): + orch = self._make_orchestrator() + technical = MagicMock(agent_name="technical") + technical.run.return_value = self._stage_result( + "technical", + total_steps=2, + tool_calls_log=[{"step": 1, "tool": "quote", "success": True}], + ) + decision = MagicMock(agent_name="decision") + decision.run.return_value = self._stage_result( + "decision", + total_steps=1, + tool_calls_log=[{"step": 1, "tool": "trend", "success": True}], + ) + + with patch.object(orch, "_build_agent_chain", return_value=[technical, decision]): + result = orch._execute_pipeline(AgentContext(query="test"), parse_dashboard=False) + + assert [item["stage_name"] for item in result.stage_trajectories] == ["technical", "decision"] + assert [item["total_steps"] for item in result.stage_trajectories] == [2, 1] + assert result.stage_trajectories[0]["tool_calls_log"][0]["tool"] == "quote" + assert "raw_text" not in result.stage_trajectories[0] + + def test_specialist_stage_trajectories_keep_scheduler_order(self): + orch = self._make_orchestrator() + orch.mode = "specialist" + technical = MagicMock(agent_name="technical") + technical.run.return_value = self._stage_result("technical", total_steps=1) + decision = MagicMock(agent_name="decision") + decision.run.return_value = self._stage_result("decision", total_steps=1) + first = self._stage_result("strategy_bull", total_steps=2) + second = self._stage_result("strategy_volume", total_steps=3) + batch = SkillBatchResult(stage_results=[first, second], opinions=[]) + + with patch.object(orch, "_build_agent_chain", return_value=[technical, decision]): + with patch.object(orch, "_build_specialist_agents", return_value=[MagicMock(), MagicMock()]): + with patch.object(orch, "_run_specialist_agent_batch", return_value=batch): + result = orch._execute_pipeline(AgentContext(query="test"), parse_dashboard=False) + + assert [item["stage_name"] for item in result.stage_trajectories] == [ + "technical", "strategy_bull", "strategy_volume", "decision" + ] + + def test_budget_boundary_adds_explicit_skipped_snapshot(self): + orch = self._make_orchestrator(config=SimpleNamespace(agent_orchestrator_timeout_s=20)) + technical = MagicMock(agent_name="technical") + technical.run.return_value = self._stage_result("technical", total_steps=1) + intel = MagicMock(agent_name="intel") + times = iter([0.0, 0.2, 0.3, 14.6, 14.7]) + + with patch.object(orch, "_build_agent_chain", return_value=[technical, intel]): + with patch("src.agent.orchestrator.time.time", side_effect=lambda: next(times, 100.0)): + result = orch._execute_pipeline(AgentContext(query="test")) + + assert result.stage_trajectories[-1]["stage_name"] == "intel" + assert result.stage_trajectories[-1]["status"] == "skipped" + assert result.stage_trajectories[-1]["failure_reason"] == "budget_skip" + def test_execute_pipeline_degrades_on_intel_failure(self): orch = self._make_orchestrator() ctx = AgentContext(query="test", stock_code="600519") @@ -1978,13 +2048,21 @@ def test_run_wraps_orchestrator_result(self): from src.agent.orchestrator import OrchestratorResult orch = self._make_orchestrator() - fake_result = OrchestratorResult(success=True, content="done", total_steps=2, total_tokens=11, model="x") + fake_result = OrchestratorResult( + success=True, + content="done", + total_steps=2, + total_tokens=11, + model="x", + stage_trajectories=[{"stage_name": "technical", "status": "completed"}], + ) with patch.object(orch, "_execute_pipeline", return_value=fake_result): result = orch.run("Analyze 600519") self.assertTrue(result.success) self.assertEqual(result.content, "done") self.assertEqual(result.total_steps, 2) + self.assertEqual(result.stage_trajectories[0]["stage_name"], "technical") def test_chat_loads_prior_history_into_context(self): from src.agent.orchestrator import OrchestratorResult diff --git a/tests/test_strategy_scheduler.py b/tests/test_strategy_scheduler.py index 0cd8c74398c..4b218fd6a6f 100644 --- a/tests/test_strategy_scheduler.py +++ b/tests/test_strategy_scheduler.py @@ -64,6 +64,10 @@ def run_stage(agent, ctx, progress_callback=None, timeout_seconds=None): [opinion.agent_name for opinion in batch.opinions], ["skill_bull_trend", "skill_hot_theme", "skill_fund_flow"], ) + self.assertEqual( + [result.stage_name for result in batch.stage_results], + ["skill_bull_trend", "skill_hot_theme", "skill_fund_flow"], + ) self.assertEqual(ctx.opinions, []) def test_runs_four_selected_skills_when_concurrency_is_four(self):