Repository navigation
Expand file tree
/
Copy pathrun_analysis.py
More file actions
130 lines (104 loc) · 4.53 KB
/
Copy pathrun_analysis.py
File metadata and controls
130 lines (104 loc) · 4.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""
CLI entry point for the Yidu-Zhixun failure analysis pipeline.
Usage:
python run_analysis.py --input test_data/model_correct_agent_wrong.jsonl
python run_analysis.py --input data/cases.jsonl --output results/run1.jsonl --limit 10
python run_analysis.py --input data/cases.jsonl --case_ids Text-1,Text-2
python run_analysis.py --input data/cases.jsonl --trace results/trace.jsonl
"""
from __future__ import annotations
import argparse
import asyncio
import logging
import os
from datetime import datetime, timezone, timedelta
from pathlib import Path
from tqdm import tqdm
from src.config.config import load_config
from src.data.dataloader import iter_cases
from src.pipeline.failure_analyzer import analyze_case
from src.utils.result_writer import ResultWriter
from src.utils.trace import TraceLogger
_TZ_CST = timezone(timedelta(hours=8))
logging.basicConfig(
level=getattr(logging, os.environ.get("LOG_LEVEL", "INFO").upper(), logging.INFO),
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Agent failure root-cause analysis pipeline")
parser.add_argument("--input", required=True, help="Path to input JSONL file")
parser.add_argument("--output", default="", help="Path to output JSONL file (overrides conf.yaml)")
parser.add_argument("--conf", default="", help="Path to conf.yaml (auto-detected if omitted)")
parser.add_argument("--limit", type=int, default=None, help="Max number of cases to process")
parser.add_argument("--case_ids", default="", help="Comma-separated case IDs to process (subset)")
parser.add_argument("--trace", default="", help="Path to trace JSONL file (omit to disable tracing)")
parser.add_argument(
"--problem_type",
default="agent_failure_q2",
help="Problem type (reserved for future problem types)",
)
return parser.parse_args()
async def main() -> None:
args = parse_args()
cfg = load_config(args.conf)
run_id = "analysis_" + datetime.now(_TZ_CST).strftime("%Y%m%dT%H%M%S")
logger.info(f"Starting run_id={run_id}")
# Initialize trace logger if path provided
trace_path = args.trace or cfg.analysis.trace_path
if trace_path:
TraceLogger.init(trace_path, run_id)
logger.info(f"Trace logging enabled: {trace_path}")
output_path = args.output or cfg.analysis.output_path
writer = ResultWriter(output_path)
logger.info(f"Output: {output_path}")
# Resume: collect already-done IDs
done_ids: set[str] = set()
if cfg.analysis.resume:
done_ids = writer.load_done_ids()
if done_ids:
logger.info(f"Resuming: {len(done_ids)} cases already done, will skip them.")
# Optional case_id filter
case_id_filter: set[str] | None = None
if args.case_ids:
case_id_filter = {cid.strip() for cid in args.case_ids.split(",")}
cases = list(iter_cases(args.input, limit=args.limit))
# Filter
pending = [
c for c in cases
if c.id not in done_ids and (case_id_filter is None or c.id in case_id_filter)
]
logger.info(f"Total cases: {len(cases)}, pending: {len(pending)}")
if not pending:
logger.info("Nothing to do.")
return
semaphore = asyncio.Semaphore(cfg.analysis.concurrency)
errors = 0
async def _run_one(case):
nonlocal errors
async with semaphore:
result = await analyze_case(case, cfg)
writer.write(result)
if result.error:
errors += 1
logger.warning(f"Case {result.case_id}: outer error: {result.error}")
else:
status = result.final.primary_cause if result.final else "?"
logger.info(f"Case {result.case_id}: {status}")
return result
tasks = [_run_one(c) for c in pending]
with tqdm(total=len(pending), desc="Analyzing cases") as pbar:
for coro in asyncio.as_completed(tasks):
result = await coro
status = "ERROR" if result.error else (result.final.primary_cause if result.final else "?")
pbar.set_postfix(last=f"{result.case_id}={status}")
pbar.update(1)
logger.info(f"Done. Results written to: {output_path}")
if errors:
logger.warning(f"{errors} cases had errors (check output for 'error' field).")
tl = TraceLogger.get()
if tl:
tl.close()
logger.info(f"Trace written to: {trace_path}")
if __name__ == "__main__":
asyncio.run(main())