Blame view

scripts/evaluation/eval_framework/cli.py 16.6 KB
c81b0fc1   tangwang   scripts/evaluatio...
1
2
3
4
5
6
  """CLI: build annotations, batch eval, audit, serve web UI."""
  
  from __future__ import annotations
  
  import argparse
  import json
cdd8ee3a   tangwang   eval框架日志独立
7
  import logging
c81b0fc1   tangwang   scripts/evaluatio...
8
  from pathlib import Path
bdb65283   tangwang   标注框架 批量标注
9
  from typing import Any, Dict
c81b0fc1   tangwang   scripts/evaluatio...
10
  
c81b0fc1   tangwang   scripts/evaluatio...
11
  from .framework import SearchEvaluationFramework
cdd8ee3a   tangwang   eval框架日志独立
12
  from .logging_setup import setup_eval_logging
c81b0fc1   tangwang   scripts/evaluatio...
13
14
15
  from .utils import ensure_dir, utc_now_iso, utc_timestamp
  from .web_app import create_web_app
  
cdd8ee3a   tangwang   eval框架日志独立
16
17
  _cli_log = logging.getLogger("search_eval.cli")
  
c81b0fc1   tangwang   scripts/evaluatio...
18
  
bdb65283   tangwang   标注框架 批量标注
19
20
21
22
23
  def add_judge_llm_args(p: argparse.ArgumentParser) -> None:
      p.add_argument(
          "--judge-model",
          default=None,
          metavar="MODEL",
331861d5   tangwang   eval框架配置化
24
          help="Judge LLM model (default: config.yaml search_evaluation.judge_model).",
bdb65283   tangwang   标注框架 批量标注
25
26
27
28
29
      )
      p.add_argument(
          "--enable-thinking",
          action=argparse.BooleanOptionalAction,
          default=None,
331861d5   tangwang   eval框架配置化
30
          help="enable_thinking for DashScope (default: search_evaluation.judge_enable_thinking).",
bdb65283   tangwang   标注框架 批量标注
31
32
33
34
35
      )
      p.add_argument(
          "--dashscope-batch",
          action=argparse.BooleanOptionalAction,
          default=None,
331861d5   tangwang   eval框架配置化
36
          help="DashScope Batch File API vs sync chat (default: search_evaluation.judge_dashscope_batch).",
bdb65283   tangwang   标注框架 批量标注
37
38
39
      )
  
  
cdd8ee3a   tangwang   eval框架日志独立
40
41
42
43
44
  def add_intent_llm_args(p: argparse.ArgumentParser) -> None:
      p.add_argument(
          "--intent-model",
          default=None,
          metavar="MODEL",
331861d5   tangwang   eval框架配置化
45
          help="Query-intent LLM model before relevance judging (default: search_evaluation.intent_model).",
cdd8ee3a   tangwang   eval框架日志独立
46
47
48
49
50
      )
      p.add_argument(
          "--intent-enable-thinking",
          action=argparse.BooleanOptionalAction,
          default=None,
331861d5   tangwang   eval框架配置化
51
          help="enable_thinking for intent model (default: search_evaluation.intent_enable_thinking).",
cdd8ee3a   tangwang   eval框架日志独立
52
53
54
      )
  
  
bdb65283   tangwang   标注框架 批量标注
55
56
57
58
59
60
61
62
  def framework_kwargs_from_args(args: argparse.Namespace) -> Dict[str, Any]:
      kw: Dict[str, Any] = {}
      if args.judge_model is not None:
          kw["judge_model"] = args.judge_model
      if args.enable_thinking is not None:
          kw["enable_thinking"] = args.enable_thinking
      if args.dashscope_batch is not None:
          kw["use_dashscope_batch"] = args.dashscope_batch
cdd8ee3a   tangwang   eval框架日志独立
63
64
65
66
      if getattr(args, "intent_model", None) is not None:
          kw["intent_model"] = args.intent_model
      if getattr(args, "intent_enable_thinking", None) is not None:
          kw["intent_enable_thinking"] = args.intent_enable_thinking
bdb65283   tangwang   标注框架 批量标注
67
68
69
      return kw
  
  
331861d5   tangwang   eval框架配置化
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
  def _apply_search_evaluation_cli_defaults(args: argparse.Namespace) -> None:
      """Fill None CLI defaults from ``config.yaml`` ``search_evaluation`` (via ``get_app_config()``)."""
      from config.loader import get_app_config
  
      se = get_app_config().search_evaluation
      if getattr(args, "tenant_id", None) in (None, ""):
          args.tenant_id = se.default_tenant_id
      if getattr(args, "queries_file", None) in (None, ""):
          args.queries_file = str(se.queries_file)
      if getattr(args, "language", None) in (None, ""):
          args.language = se.default_language
  
      if args.command == "serve":
          if getattr(args, "host", None) in (None, ""):
              args.host = se.web_host
          if getattr(args, "port", None) is None:
              args.port = se.web_port
  
      if args.command == "batch":
          if getattr(args, "top_k", None) is None:
              args.top_k = se.batch_top_k
  
      if args.command == "audit":
          if getattr(args, "top_k", None) is None:
              args.top_k = se.audit_top_k
          if getattr(args, "limit_suspicious", None) is None:
              args.limit_suspicious = se.audit_limit_suspicious
  
      if args.command == "build":
          if getattr(args, "search_depth", None) is None:
              args.search_depth = se.build_search_depth
          if getattr(args, "rerank_depth", None) is None:
              args.rerank_depth = se.build_rerank_depth
          if getattr(args, "annotate_search_top_k", None) is None:
              args.annotate_search_top_k = se.annotate_search_top_k
          if getattr(args, "annotate_rerank_top_k", None) is None:
              args.annotate_rerank_top_k = se.annotate_rerank_top_k
          if getattr(args, "search_recall_top_k", None) is None:
              args.search_recall_top_k = se.search_recall_top_k
          if getattr(args, "rerank_high_threshold", None) is None:
              args.rerank_high_threshold = se.rerank_high_threshold
          if getattr(args, "rerank_high_skip_count", None) is None:
              args.rerank_high_skip_count = se.rerank_high_skip_count
          if getattr(args, "rebuild_llm_batch_size", None) is None:
              args.rebuild_llm_batch_size = se.rebuild_llm_batch_size
          if getattr(args, "rebuild_min_batches", None) is None:
              args.rebuild_min_batches = se.rebuild_min_llm_batches
          if getattr(args, "rebuild_max_batches", None) is None:
              args.rebuild_max_batches = se.rebuild_max_llm_batches
          if getattr(args, "rebuild_irrelevant_stop_ratio", None) is None:
              args.rebuild_irrelevant_stop_ratio = se.rebuild_irrelevant_stop_ratio
          if getattr(args, "rebuild_irrel_low_combined_stop_ratio", None) is None:
              args.rebuild_irrel_low_combined_stop_ratio = se.rebuild_irrel_low_combined_stop_ratio
          if getattr(args, "rebuild_irrelevant_stop_streak", None) is None:
              args.rebuild_irrelevant_stop_streak = se.rebuild_irrelevant_stop_streak
  
  
c81b0fc1   tangwang   scripts/evaluatio...
127
128
129
130
131
  def build_cli_parser() -> argparse.ArgumentParser:
      parser = argparse.ArgumentParser(description="Search evaluation annotation builder and web UI")
      sub = parser.add_subparsers(dest="command", required=True)
  
      build = sub.add_parser("build", help="Build pooled annotation set for queries")
331861d5   tangwang   eval框架配置化
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
      build.add_argument(
          "--tenant-id",
          default=None,
          help="Tenant id (default: search_evaluation.default_tenant_id in config.yaml).",
      )
      build.add_argument(
          "--queries-file",
          default=None,
          help="Query list file (default: search_evaluation.queries_file).",
      )
      build.add_argument(
          "--search-depth",
          type=int,
          default=None,
          help="Default: search_evaluation.build_search_depth.",
      )
      build.add_argument(
          "--rerank-depth",
          type=int,
          default=None,
          help="Default: search_evaluation.build_rerank_depth.",
      )
      build.add_argument(
          "--annotate-search-top-k",
          type=int,
          default=None,
          help="Default: search_evaluation.annotate_search_top_k.",
      )
      build.add_argument(
          "--annotate-rerank-top-k",
          type=int,
          default=None,
          help="Default: search_evaluation.annotate_rerank_top_k.",
      )
d172c259   tangwang   eval框架
166
167
168
169
      build.add_argument(
          "--search-recall-top-k",
          type=int,
          default=None,
dedd31c5   tangwang   1. 搜索 recall 池「1 ...
170
          help="Rebuild mode only: top-K search hits enter recall pool with score 1 (default when --force-refresh-labels: 200).",
d172c259   tangwang   eval框架
171
172
173
174
175
176
177
178
179
180
181
182
183
184
      )
      build.add_argument(
          "--rerank-high-threshold",
          type=float,
          default=None,
          help="Rebuild only: count rerank scores above this on non-pool docs (default 0.5).",
      )
      build.add_argument(
          "--rerank-high-skip-count",
          type=int,
          default=None,
          help="Rebuild only: skip query if more than this many non-pool docs have rerank score > threshold (default 1000).",
      )
      build.add_argument("--rebuild-llm-batch-size", type=int, default=None, help="Rebuild only: LLM batch size (default 50).")
dedd31c5   tangwang   1. 搜索 recall 池「1 ...
185
      build.add_argument("--rebuild-min-batches", type=int, default=None, help="Rebuild only: min LLM batches before early stop (default 10).")
d172c259   tangwang   eval框架
186
187
188
189
190
      build.add_argument("--rebuild-max-batches", type=int, default=None, help="Rebuild only: max LLM batches (default 40).")
      build.add_argument(
          "--rebuild-irrelevant-stop-ratio",
          type=float,
          default=None,
331861d5   tangwang   eval框架配置化
191
          help="Rebuild only: bad batch requires irrelevant_ratio > this (default: search_evaluation.rebuild_irrelevant_stop_ratio).",
dedd31c5   tangwang   1. 搜索 recall 池「1 ...
192
193
194
195
196
      )
      build.add_argument(
          "--rebuild-irrel-low-combined-stop-ratio",
          type=float,
          default=None,
35ae3b29   tangwang   批量评估框架,召回参数修改和llm...
197
          help="Rebuild only: bad batch requires (irrelevant+low)/n > this (default 0.959).",
d172c259   tangwang   eval框架
198
199
200
201
202
      )
      build.add_argument(
          "--rebuild-irrelevant-stop-streak",
          type=int,
          default=None,
35ae3b29   tangwang   批量评估框架,召回参数修改和llm...
203
          help="Rebuild only: consecutive bad batches (both thresholds strict >) before early stop (default 3).",
d172c259   tangwang   eval框架
204
      )
331861d5   tangwang   eval框架配置化
205
206
207
208
209
      build.add_argument(
          "--language",
          default=None,
          help="Default: search_evaluation.default_language.",
      )
c81b0fc1   tangwang   scripts/evaluatio...
210
211
      build.add_argument("--force-refresh-rerank", action="store_true")
      build.add_argument("--force-refresh-labels", action="store_true")
bdb65283   tangwang   标注框架 批量标注
212
      add_judge_llm_args(build)
cdd8ee3a   tangwang   eval框架日志独立
213
      add_intent_llm_args(build)
c81b0fc1   tangwang   scripts/evaluatio...
214
215
  
      batch = sub.add_parser("batch", help="Run batch evaluation against live search")
331861d5   tangwang   eval框架配置化
216
217
218
219
      batch.add_argument("--tenant-id", default=None, help="Default: search_evaluation.default_tenant_id.")
      batch.add_argument("--queries-file", default=None, help="Default: search_evaluation.queries_file.")
      batch.add_argument("--top-k", type=int, default=None, help="Default: search_evaluation.batch_top_k.")
      batch.add_argument("--language", default=None, help="Default: search_evaluation.default_language.")
c81b0fc1   tangwang   scripts/evaluatio...
220
      batch.add_argument("--force-refresh-labels", action="store_true")
bdb65283   tangwang   标注框架 批量标注
221
      add_judge_llm_args(batch)
cdd8ee3a   tangwang   eval框架日志独立
222
      add_intent_llm_args(batch)
c81b0fc1   tangwang   scripts/evaluatio...
223
224
  
      audit = sub.add_parser("audit", help="Audit annotation quality for queries")
331861d5   tangwang   eval框架配置化
225
226
227
228
229
230
231
232
233
234
      audit.add_argument("--tenant-id", default=None, help="Default: search_evaluation.default_tenant_id.")
      audit.add_argument("--queries-file", default=None, help="Default: search_evaluation.queries_file.")
      audit.add_argument("--top-k", type=int, default=None, help="Default: search_evaluation.audit_top_k.")
      audit.add_argument("--language", default=None, help="Default: search_evaluation.default_language.")
      audit.add_argument(
          "--limit-suspicious",
          type=int,
          default=None,
          help="Default: search_evaluation.audit_limit_suspicious.",
      )
c81b0fc1   tangwang   scripts/evaluatio...
235
      audit.add_argument("--force-refresh-labels", action="store_true")
bdb65283   tangwang   标注框架 批量标注
236
      add_judge_llm_args(audit)
cdd8ee3a   tangwang   eval框架日志独立
237
      add_intent_llm_args(audit)
c81b0fc1   tangwang   scripts/evaluatio...
238
239
  
      serve = sub.add_parser("serve", help="Serve evaluation web UI on port 6010")
331861d5   tangwang   eval框架配置化
240
241
242
243
      serve.add_argument("--tenant-id", default=None, help="Default: search_evaluation.default_tenant_id.")
      serve.add_argument("--queries-file", default=None, help="Default: search_evaluation.queries_file.")
      serve.add_argument("--host", default=None, help="Default: search_evaluation.web_host.")
      serve.add_argument("--port", type=int, default=None, help="Default: search_evaluation.web_port.")
bdb65283   tangwang   标注框架 批量标注
244
      add_judge_llm_args(serve)
cdd8ee3a   tangwang   eval框架日志独立
245
      add_intent_llm_args(serve)
c81b0fc1   tangwang   scripts/evaluatio...
246
247
248
249
250
  
      return parser
  
  
  def run_build(args: argparse.Namespace) -> None:
a345b01f   tangwang   eval framework
251
      framework = SearchEvaluationFramework(tenant_id=args.tenant_id, **framework_kwargs_from_args(args))
c81b0fc1   tangwang   scripts/evaluatio...
252
253
      queries = framework.queries_from_file(Path(args.queries_file))
      summary = []
d172c259   tangwang   eval框架
254
255
256
      rebuild_kwargs = {}
      if args.force_refresh_labels:
          rebuild_kwargs = {
331861d5   tangwang   eval框架配置化
257
258
259
260
261
262
263
264
265
              "search_recall_top_k": args.search_recall_top_k,
              "rerank_high_threshold": args.rerank_high_threshold,
              "rerank_high_skip_count": args.rerank_high_skip_count,
              "rebuild_llm_batch_size": args.rebuild_llm_batch_size,
              "rebuild_min_batches": args.rebuild_min_batches,
              "rebuild_max_batches": args.rebuild_max_batches,
              "rebuild_irrelevant_stop_ratio": args.rebuild_irrelevant_stop_ratio,
              "rebuild_irrel_low_combined_stop_ratio": args.rebuild_irrel_low_combined_stop_ratio,
              "rebuild_irrelevant_stop_streak": args.rebuild_irrelevant_stop_streak,
d172c259   tangwang   eval框架
266
          }
331861d5   tangwang   eval框架配置化
267
268
269
      total_q = len(queries)
      for q_index, query in enumerate(queries, start=1):
          _cli_log.info("[build] (%s/%s) starting query=%r", q_index, total_q, query)
c81b0fc1   tangwang   scripts/evaluatio...
270
271
272
273
274
275
276
277
278
          result = framework.build_query_annotation_set(
              query=query,
              search_depth=args.search_depth,
              rerank_depth=args.rerank_depth,
              annotate_search_top_k=args.annotate_search_top_k,
              annotate_rerank_top_k=args.annotate_rerank_top_k,
              language=args.language,
              force_refresh_rerank=args.force_refresh_rerank,
              force_refresh_labels=args.force_refresh_labels,
d172c259   tangwang   eval框架
279
              **rebuild_kwargs,
c81b0fc1   tangwang   scripts/evaluatio...
280
281
282
283
284
285
286
287
288
289
290
          )
          summary.append(
              {
                  "query": result.query,
                  "search_total": result.search_total,
                  "search_depth": result.search_depth,
                  "rerank_corpus_size": result.rerank_corpus_size,
                  "annotated_count": result.annotated_count,
                  "output_json_path": str(result.output_json_path),
              }
          )
cdd8ee3a   tangwang   eval框架日志独立
291
292
293
294
295
296
297
298
          _cli_log.info(
              "[build] query=%r search_total=%s search_depth=%s corpus=%s annotated=%s output=%s",
              result.query,
              result.search_total,
              result.search_depth,
              result.rerank_corpus_size,
              result.annotated_count,
              result.output_json_path,
c81b0fc1   tangwang   scripts/evaluatio...
299
300
301
          )
      out_path = ensure_dir(framework.artifact_root / "query_builds") / f"build_summary_{utc_timestamp()}.json"
      out_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
cdd8ee3a   tangwang   eval框架日志独立
302
      _cli_log.info("[done] summary=%s", out_path)
c81b0fc1   tangwang   scripts/evaluatio...
303
304
305
  
  
  def run_batch(args: argparse.Namespace) -> None:
a345b01f   tangwang   eval framework
306
      framework = SearchEvaluationFramework(tenant_id=args.tenant_id, **framework_kwargs_from_args(args))
c81b0fc1   tangwang   scripts/evaluatio...
307
      queries = framework.queries_from_file(Path(args.queries_file))
331861d5   tangwang   eval框架配置化
308
      _cli_log.info("[batch] queries_file=%s count=%s", args.queries_file, len(queries))
c81b0fc1   tangwang   scripts/evaluatio...
309
310
311
312
313
314
315
      payload = framework.batch_evaluate(
          queries=queries,
          top_k=args.top_k,
          auto_annotate=True,
          language=args.language,
          force_refresh_labels=args.force_refresh_labels,
      )
cdd8ee3a   tangwang   eval框架日志独立
316
      _cli_log.info("[done] batch_id=%s aggregate_metrics=%s", payload["batch_id"], payload["aggregate_metrics"])
c81b0fc1   tangwang   scripts/evaluatio...
317
318
319
  
  
  def run_audit(args: argparse.Namespace) -> None:
a345b01f   tangwang   eval framework
320
      framework = SearchEvaluationFramework(tenant_id=args.tenant_id, **framework_kwargs_from_args(args))
c81b0fc1   tangwang   scripts/evaluatio...
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
      queries = framework.queries_from_file(Path(args.queries_file))
      audit_items = []
      for query in queries:
          item = framework.audit_live_query(
              query=query,
              top_k=args.top_k,
              language=args.language,
              auto_annotate=not args.force_refresh_labels,
          )
          if args.force_refresh_labels:
              live_payload = framework.search_client.search(query=query, size=max(args.top_k, 100), from_=0, language=args.language)
              framework.annotate_missing_labels(
                  query=query,
                  docs=list(live_payload.get("results") or [])[: args.top_k],
                  force_refresh=True,
              )
              item = framework.audit_live_query(
                  query=query,
                  top_k=args.top_k,
                  language=args.language,
                  auto_annotate=False,
              )
          audit_items.append(
              {
                  "query": query,
                  "metrics": item["metrics"],
                  "distribution": item["distribution"],
                  "suspicious_count": len(item["suspicious"]),
                  "suspicious_examples": item["suspicious"][: args.limit_suspicious],
              }
          )
cdd8ee3a   tangwang   eval框架日志独立
352
353
354
355
356
          _cli_log.info(
              "[audit] query=%r suspicious=%s metrics=%s",
              query,
              len(item["suspicious"]),
              item["metrics"],
c81b0fc1   tangwang   scripts/evaluatio...
357
358
359
360
361
362
363
364
365
366
367
368
          )
  
      summary = {
          "created_at": utc_now_iso(),
          "tenant_id": args.tenant_id,
          "top_k": args.top_k,
          "query_count": len(queries),
          "total_suspicious": sum(item["suspicious_count"] for item in audit_items),
          "queries": audit_items,
      }
      out_path = ensure_dir(framework.artifact_root / "audits") / f"audit_{utc_timestamp()}.json"
      out_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
cdd8ee3a   tangwang   eval框架日志独立
369
      _cli_log.info("[done] audit=%s", out_path)
c81b0fc1   tangwang   scripts/evaluatio...
370
371
372
  
  
  def run_serve(args: argparse.Namespace) -> None:
a345b01f   tangwang   eval framework
373
      framework = SearchEvaluationFramework(tenant_id=args.tenant_id, **framework_kwargs_from_args(args))
c81b0fc1   tangwang   scripts/evaluatio...
374
375
376
377
378
379
380
      app = create_web_app(framework, Path(args.queries_file))
      import uvicorn
  
      uvicorn.run(app, host=args.host, port=args.port, log_level="info")
  
  
  def main() -> None:
331861d5   tangwang   eval框架配置化
381
382
383
384
      from config.loader import get_app_config
  
      se = get_app_config().search_evaluation
      log_file = setup_eval_logging(se.eval_log_dir)
c81b0fc1   tangwang   scripts/evaluatio...
385
386
      parser = build_cli_parser()
      args = parser.parse_args()
331861d5   tangwang   eval框架配置化
387
      _apply_search_evaluation_cli_defaults(args)
cdd8ee3a   tangwang   eval框架日志独立
388
389
390
391
      logging.getLogger("search_eval").info(
          "CLI start command=%s tenant_id=%s log_file=%s",
          args.command,
          getattr(args, "tenant_id", ""),
331861d5   tangwang   eval框架配置化
392
          log_file.resolve(),
cdd8ee3a   tangwang   eval框架日志独立
393
      )
c81b0fc1   tangwang   scripts/evaluatio...
394
395
396
397
398
399
400
401
402
403
404
405
406
      if args.command == "build":
          run_build(args)
          return
      if args.command == "batch":
          run_batch(args)
          return
      if args.command == "audit":
          run_audit(args)
          return
      if args.command == "serve":
          run_serve(args)
          return
      raise SystemExit(f"unknown command: {args.command}")