File size: 26,835 Bytes
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
131
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
#!/usr/bin/env python3
"""Trajectory evaluation script for LandingPageGenerator-H_A2A.

Evaluates 6 metrics:
  1) Exact match
  2) In-order match
  3) Any-order match
  4) Precision
  5) Recall
  6) Single-tool use
"""

import os
import re
import yaml
from pathlib import Path
from typing import List, Dict, Tuple, Set
from collections import defaultdict
import pandas as pd
import math


class TrajectoryParser:
    """Parse an execution_path.md file and extract the full execution trajectory."""

    def __init__(self, md_file_path: str, extract_types: List[str] = None):
        """
        Args:
            md_file_path: Path to execution_path.md
            extract_types: Node types to extract. Default: ['Tool'].
                          Options: 'SPAN', 'Chain', 'Tool', 'AGENT', 'LLM', 'Task Created', 'Crew Created'
        """
        self.md_file_path = md_file_path
        self.extract_types = extract_types or ["Tool"]
        self.trajectory = []

    def parse(self) -> List[str]:
        """Parse the file and return a list of actions (trajectory)."""
        if not os.path.exists(self.md_file_path):
            return []

        with open(self.md_file_path, "r", encoding="utf-8") as f:
            content = f.read()

        # Extract the "Execution Path Tree" section (inside a code block)
        tree_match = re.search(
            r"## Execution Path Tree.*?```\n(.*?)```", content, re.DOTALL
        )
        if not tree_match:
            return []

        tree_content = tree_match.group(1)
        trajectory = []

        for line in tree_content.split("\n"):
            # Remove tree drawing characters and keep node text
            clean_line = re.sub(r"^[│├└─\s]+", "", line).strip()
            if not clean_line:
                continue

            # Remove error marker ❌
            clean_line = re.sub(r"^❌\s+", "", clean_line)

            # Remove retry markers: (retry N) and [RETRYN]
            clean_line = re.sub(r"\s*\(retry\s+\d+\)", "", clean_line)
            clean_line = re.sub(r"\s*\[RETRY\d+\]", "", clean_line)

            # Remove ERROR info (strip the [ERROR:...] suffix)
            clean_line = re.sub(r"\s*\[ERROR:[^\]]*\]", "", clean_line)

            # Extract node info
            node_info = self._extract_node_info(clean_line)

            if node_info and node_info["type"] in self.extract_types:
                trajectory.append(node_info["action"])

        self.trajectory = trajectory
        return trajectory

    def _extract_node_info(self, line: str) -> dict:
        """Extract node info from one line.

        Note: the input line should already have markers like ❌, RETRY, and [ERROR:...] removed.

        Returns:
            {'type': str, 'action': str} or None
        """
        # SPAN node: [SPAN] span_name [stats]
        # Use a permissive regex to handle leftover special chars.
        span_match = re.match(r"\[SPAN\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line)
        if span_match:
            span_name = span_match.group(1).strip()
            return {"type": "SPAN", "action": f"SPAN: {span_name}"}

        # Chain node: [Chain] chain_name [stats]
        # For Crew_<uuid>.kickoff, normalize to Crew***.kickoff.
        chain_match = re.match(r"\[Chain\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line)
        if chain_match:
            chain_name = chain_match.group(1).strip()
            # Wildcard normalization: Crew_UUID.kickoff -> Crew***.kickoff
            chain_name = re.sub(
                r"Crew_[a-f0-9\-]+\.kickoff", "Crew***.kickoff", chain_name
            )
            return {"type": "Chain", "action": f"Chain: {chain_name}"}

        # AGENT node: [AGENT] agent_name._execute_core [stats]
        agent_match = re.match(r"\[AGENT\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line)
        if agent_match:
            agent_name = agent_match.group(1).strip()
            # Remove the ._execute_core suffix
            agent_name = re.sub(r"\._execute_core$", "", agent_name)
            return {"type": "AGENT", "action": f"AGENT: {agent_name}"}

        # Tool node: [Tool] tool_name._use [time]
        tool_match = re.match(
            r"\[Tool\]\s+([^\[\]]+?)(?:\s+\[[\d.]+(?:ms|s)\])?(?:\s*@@@)?\s*$", line
        )
        if tool_match:
            tool_name = tool_match.group(1).strip()
            # NOTE: tool naming differs across frameworks; keep the raw name.
            # LangGraph: bocha_websearch_tool (no suffix)
            # AutoGen: execute_tool xxx (prefix)
            # CrewAI: xxx._use (suffix)
            # Therefore we do not strip ._use.
            return {"type": "Tool", "action": f"Tool: {tool_name}"}

        # LLM node: [LLM] model_name (tokens) [time]
        llm_match = re.match(r"\[LLM\]\s+([^\(\[]+)", line)
        if llm_match:
            model_name = llm_match.group(1).strip()
            return {"type": "LLM", "action": f"LLM: {model_name}"}

        # Task Created node
        task_match = re.match(r"\[Task Created\]", line)
        if task_match:
            return {"type": "Task Created", "action": "Task Created"}

        # Crew Created node
        crew_match = re.match(r"\[Crew Created\]", line)
        if crew_match:
            return {"type": "Crew Created", "action": "Crew Created"}

        return None


class TrajectoryEvaluator:
    """Trajectory evaluator implementing 6 metrics.

    A2A_mix characteristic: supports dynamic reference trajectory selection.
    """

    def __init__(self, reference_trajectory: List[str]):
        """
        Args:
            reference_trajectory: Reference trajectory (ground truth)
        """
        self.reference = reference_trajectory

    def _match_action(self, predicted_action: str, reference_action: str) -> bool:
        """
        Match two actions with wildcard support.

        Args:
            predicted_action: Action from the observed trajectory
            reference_action: Action from the reference trajectory (may contain wildcards)

        Returns:
            True if match, False otherwise
        """
        # Exact match
        if predicted_action == reference_action:
            return True

        # Wildcard: "LLM: *" matches any "LLM: <model_name>"
        if reference_action == "LLM: *" and predicted_action.startswith("LLM: "):
            return True

        return False

    @staticmethod
    def detect_autogen_tools(predicted: List[str]) -> List[str]:
        """Detect the tool calls inside the AutoGen phase (generic version).

        Returns:
            A list of tool action strings in appearance order. Empty if not found.
            Example: ['Tool: execute_tool learn_landing_page_options']
        """
        # Locate invoke_agent (generic match)
        start_idx = -1
        for i, s in enumerate(predicted):
            if s.startswith("AGENT: invoke_agent "):
                start_idx = i
                break

        if start_idx == -1:
            return []

        # Extract tools under invoke_agent
        tools = []
        i = start_idx + 1

        # Find the next SPAN (end of AutoGen phase)
        while i < len(predicted):
            s = predicted[i]
            if s.startswith("SPAN: "):
                break

            if s.startswith("Tool: execute_tool "):
                tools.append(s)

            i += 1

        return tools

    @staticmethod
    def generate_autogen_llm_patterns(num_tools: int) -> List[List[int]]:
        """Generate all possible LLM insertion patterns between AutoGen tools.

        Args:
            num_tools: Number of tools

        Returns:
            A list of binary patterns. Each pattern is a list indicating whether an LLM is inserted
            between adjacent tools.
            Example for num_tools=2: [[0], [1]]
              [0] = Tool1 → Tool2 (no LLM)
              [1] = Tool1 → LLM → Tool2 (insert one LLM)
        """
        if num_tools < 2:
            return [[]]  # Fewer than 2 tools: no gaps

        # n tools have n-1 gaps
        num_gaps = num_tools - 1

        # Enumerate all 0/1 combinations: 2^(n-1) patterns
        patterns = []
        for i in range(2**num_gaps):
            pattern = []
            for j in range(num_gaps):
                # Extract bit j (0 or 1)
                pattern.append((i >> j) & 1)
            patterns.append(pattern)

        return patterns

    @staticmethod
    def build_autogen_reference_variant(
        base_reference: List[str], llm_pattern: List[int]
    ) -> List[str]:
        """Build a reference variant for the AutoGen portion given an LLM insertion pattern.

        Args:
            base_reference: Base reference trajectory
            llm_pattern: LLM insertion pattern (0=no insertion, 1=insert one LLM)

        Returns:
            The adjusted full reference trajectory
        """
        try:
            # Locate invoke_agent (generic match)
            start_idx = -1
            for i, s in enumerate(base_reference):
                if s.startswith("AGENT: invoke_agent "):
                    start_idx = i
                    break

            if start_idx == -1:
                return base_reference

            # Find the end of this phase (next SPAN or end of list)
            end_idx = len(base_reference)
            for i in range(start_idx + 1, len(base_reference)):
                if base_reference[i].startswith("SPAN: "):
                    end_idx = i
                    break

            # Extract tool list from the base reference
            tools = []
            for i in range(start_idx + 1, end_idx):
                if base_reference[i].startswith("Tool: execute_tool "):
                    tools.append(base_reference[i])

            if not tools:
                return base_reference

            # Split into three parts: before, AutoGen, after
            before = base_reference[: start_idx + 1]  # includes the AGENT line
            after = base_reference[end_idx:]  # from the next SPAN

            # Build AutoGen part based on llm_pattern
            autogen_part = ["LLM: *"]  # opening LLM

            for i, tool in enumerate(tools):
                autogen_part.append(tool)

                # If not the last tool, insert LLM if needed
                if i < len(tools) - 1 and i < len(llm_pattern):
                    if llm_pattern[i] == 1:
                        autogen_part.append("LLM: *")

            autogen_part.append("LLM: *")  # closing LLM

            # Combine into the full trajectory
            return before + autogen_part + after

        except (ValueError, IndexError):
            # If parsing fails, fall back to the original reference
            return base_reference

    def exact_match(self, predicted: List[str]) -> int:
        """
        Exact match: the predicted trajectory must match the reference exactly (with wildcard support).

        Returns:
            1 if exact match, 0 otherwise
        """
        if len(predicted) != len(self.reference):
            return 0

        for i in range(len(predicted)):
            if not self._match_action(predicted[i], self.reference[i]):
                return 0

        return 1

    def in_order_match(self, predicted: List[str]) -> int:
        """
        In-order match: the reference must be a subsequence of the predicted trajectory (wildcards supported).
        Extra actions are allowed, but required steps must appear in order.

        Returns:
            1 if in-order match, 0 otherwise
        """
        if not self.reference:
            return 1  # Empty reference always matches

        ref_idx = 0
        for pred_action in predicted:
            if ref_idx < len(self.reference) and self._match_action(
                pred_action, self.reference[ref_idx]
            ):
                ref_idx += 1

        # Check whether all reference steps were found in order
        return 1 if ref_idx == len(self.reference) else 0

    def any_order_match(self, predicted: List[str]) -> int:
        """
        Any-order match: the predicted trajectory contains all required actions (wildcards supported).
        Order does not matter; extra actions are allowed.

        Returns:
            1 if any-order match, 0 otherwise
        """
        if not self.reference:
            return 1

        # Copy predicted actions for matching
        pred_remaining = predicted.copy()

        # For each reference action, try to find a match in the predicted list
        for ref_action in self.reference:
            matched = False
            for i, pred_action in enumerate(pred_remaining):
                if self._match_action(pred_action, ref_action):
                    pred_remaining.pop(i)  # remove matched
                    matched = True
                    break

            if not matched:
                return 0  # a reference action was not matched

        return 1

    def precision(self, predicted: List[str]) -> float:
        """
        Precision: how many predicted actions are considered correct by the reference (wildcards supported).

        Precision = TP / (TP + FP)
        TP: correctly matched actions
        FP: incorrect / extra actions

        Returns:
            precision value (0.0 - 1.0)
        """
        if not predicted:
            return 1.0  # no predictions and no false positives

        if not self.reference:
            return 0.0  # empty reference but non-empty predictions => all are false positives

        # Copy reference actions for matching
        ref_remaining = self.reference.copy()

        tp = 0  # True Positives
        for pred_action in predicted:
            # Try to find a match in the reference list
            for i, ref_action in enumerate(ref_remaining):
                if self._match_action(pred_action, ref_action):
                    tp += 1
                    ref_remaining.pop(i)  # remove matched
                    break

        fp = len(predicted) - tp  # False Positives

        return tp / (tp + fp) if (tp + fp) > 0 else 0.0

    def recall(self, predicted: List[str]) -> float:
        """
        Recall: how many reference actions are covered by the predicted trajectory (wildcards supported).

        Recall = TP / (TP + FN)
        TP: covered required actions
        FN: missed required actions

        Returns:
            recall value (0.0 - 1.0)
        """
        if not self.reference:
            return 1.0  # no required actions

        if not predicted:
            return 0.0  # no predictions

        # Copy predicted actions for matching
        pred_remaining = predicted.copy()

        tp = 0  # True Positives
        for ref_action in self.reference:
            # Try to find a match in the predicted list
            for i, pred_action in enumerate(pred_remaining):
                if self._match_action(pred_action, ref_action):
                    tp += 1
                    pred_remaining.pop(i)  # remove matched
                    break

        fn = len(self.reference) - tp  # False Negatives

        return tp / (tp + fn) if (tp + fn) > 0 else 0.0

    def single_tool_use(self, predicted: List[str], tool_name: str) -> int:
        """
        Single-tool use: whether a specific tool action appears in the trajectory (wildcards supported).

        Args:
            predicted: Predicted trajectory
            tool_name: Target tool action string

        Returns:
            1 if tool is used, 0 otherwise
        """
        # Check whether any predicted action matches the tool
        for pred_action in predicted:
            if self._match_action(pred_action, tool_name):
                return 1
        return 0

    def evaluate_all(
        self, predicted: List[str], target_tools: List[str] = None
    ) -> Dict[str, float]:
        """
        Evaluate all metrics.

        Args:
            predicted: Predicted trajectory
            target_tools: Tools to check for usage (for single-tool use)

        Returns:
            A dict with metric values
        """
        results = {
            "exact_match": self.exact_match(predicted),
            "in_order_match": self.in_order_match(predicted),
            "any_order_match": self.any_order_match(predicted),
            "precision": self.precision(predicted),
            "recall": self.recall(predicted),
        }

        # Single-tool use: average usage over all target tools
        if target_tools:
            tool_usage_count = sum(
                self.single_tool_use(predicted, tool) for tool in target_tools
            )
            results["single_tool_use"] = (
                tool_usage_count / len(target_tools) if target_tools else 0.0
            )

        return results


class DatasetEvaluator:
    """Dataset-level evaluator."""

    def __init__(self, config_file: str):
        """
        Args:
            config_file: Path to the YAML config file containing reference trajectory definitions
        """
        self.config_file = config_file
        self.config = self._load_config()
        self.reference_trajectory = self.config.get("reference_trajectory", [])
        self.target_tools = self.config.get("target_tools", [])
        self.models = self.config.get("models", [])
        self.project_name = self.config.get(
            "project_name", "LandingPageGenerator-H_A2A"
        )
        # Extraction types (defaults to Tool; can be configured)
        self.extract_types = self.config.get("extract_types", ["Tool"])

        # A2A_mix: whether to enable dynamic reference matching for AutoGen LLM/Tool patterns
        self.enable_autogen_pattern_matching = self.config.get(
            "enable_autogen_pattern_matching", True
        )

    def _load_config(self) -> Dict:
        """Load the YAML config file."""
        if not os.path.exists(self.config_file):
            print(f"Config file not found: {self.config_file}")
            return {}

        with open(self.config_file, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)

    def collect_execution_paths(
        self, model_name: str, base_dir: str
    ) -> List[Tuple[str, List[str]]]:
        """Collect and parse all execution_path.md files for a model.

        Args:
            model_name: Model name
            base_dir: RESULTS directory path

        Returns:
            A list of (session_id, trajectory)
        """
        model_dir = Path(base_dir) / model_name / self.project_name / "test_results"

        if not model_dir.exists():
            print(f"Model directory not found: {model_dir}")
            return []

        results = []

        # Iterate over all session subdirectories
        for session_dir in sorted(model_dir.iterdir()):
            if not session_dir.is_dir():
                continue

            exec_path_file = session_dir / "execution_path.md"
            if not exec_path_file.exists():
                continue

            # Parse trajectory using configured extraction types
            parser = TrajectoryParser(
                str(exec_path_file), extract_types=self.extract_types
            )
            trajectory = parser.parse()

            results.append((session_dir.name, trajectory))

        return results

    def evaluate_model(self, model_name: str, base_dir: str) -> Dict[str, float]:
        """Evaluate one model across all samples.

        Args:
            model_name: Model name
            base_dir: RESULTS directory path

        Returns:
            A dict of average metric values
        """
        trajectories = self.collect_execution_paths(model_name, base_dir)

        if not trajectories:
            print(f"No trajectory data found for model {model_name}")
            return {}

        # Accumulate metrics
        all_metrics = defaultdict(list)

        for session_id, predicted in trajectories:
            # A2A_mix: dynamic reference matching for AutoGen
            reference = self.reference_trajectory

            if self.enable_autogen_pattern_matching:
                # Detect tool count in AutoGen phase
                autogen_tools = TrajectoryEvaluator.detect_autogen_tools(predicted)

                if autogen_tools:
                    num_tools = len(autogen_tools)
                    # Enumerate all possible LLM insertion patterns
                    llm_patterns = TrajectoryEvaluator.generate_autogen_llm_patterns(
                        num_tools
                    )

                    # Choose the highest-scoring variant
                    best_reference = reference
                    best_score = -1

                    for llm_pattern in llm_patterns:
                        # Build a variant
                        variant = TrajectoryEvaluator.build_autogen_reference_variant(
                            reference, llm_pattern
                        )

                        # Score with weights: exact*3 + in_order*2 + any_order*1
                        test_evaluator = TrajectoryEvaluator(variant)
                        exact = test_evaluator.exact_match(predicted)
                        in_order = test_evaluator.in_order_match(predicted)
                        any_order = test_evaluator.any_order_match(predicted)
                        score = exact * 3 + in_order * 2 + any_order * 1

                        # Select the best variant (prefer exact, then in_order, then any_order)
                        if score > best_score:
                            best_score = score
                            best_reference = variant

                    reference = best_reference

            # Evaluate
            evaluator = TrajectoryEvaluator(reference)
            metrics = evaluator.evaluate_all(predicted, self.target_tools)

            for key, value in metrics.items():
                all_metrics[key].append(value)

        # Compute averages
        avg_metrics = {}
        for key, values in all_metrics.items():
            avg_metrics[key] = sum(values) / len(values) if values else 0.0

        num_samples = len(trajectories)
        avg_metrics["num_samples"] = num_samples

        return avg_metrics

    def evaluate_all_models(self, base_dir: str = None) -> pd.DataFrame:
        """Evaluate all models and return a summary DataFrame.

        Args:
            base_dir: RESULTS directory path (defaults to two levels above this script)

        Returns:
            A DataFrame with per-model metrics
        """
        if base_dir is None:
            # Default path: two levels above this script
            base_dir = Path(__file__).parent.parent.parent

        results = []

        for model_name in self.models:
            print(f"\nEvaluating model: {model_name}")
            metrics = self.evaluate_model(model_name, str(base_dir))

            if metrics:
                metrics["model"] = model_name
                results.append(metrics)
                print(f"  Done, samples: {metrics['num_samples']}")
            else:
                print("  Skipped (no data)")

        if not results:
            print("\nNo model data available")
            return pd.DataFrame()

        # Create DataFrame
        df = pd.DataFrame(results)

        # Reorder columns (model first)
        cols = [
            "model",
            "num_samples",
            "exact_match",
            "in_order_match",
            "any_order_match",
            "precision",
            "recall",
            "single_tool_use",
            "unique_path_ratio",
            "path_entropy",
        ]

        # Keep only existing columns
        cols = [col for col in cols if col in df.columns]

        df = df[cols]

        return df


def main():
    """Main entrypoint."""
    import argparse

    parser = argparse.ArgumentParser(
        description="Evaluate trajectory metrics for LandingPageGenerator-H_A2A"
    )
    parser.add_argument(
        "--config",
        type=str,
        default="reference_trajectory.yaml",
        help="Reference trajectory config file path (YAML)",
    )
    parser.add_argument(
        "--base-dir",
        type=str,
        default=None,
        help="RESULTS directory path (defaults to two levels above this script)",
    )
    parser.add_argument(
        "--output",
        type=str,
        default="evaluation_results.csv",
        help="Output CSV file path",
    )
    parser.add_argument(
        "--format",
        type=str,
        choices=["csv", "markdown", "both"],
        default="both",
        help="Output format. NOTE: Markdown output is disabled; this option is kept for compatibility.",
    )

    args = parser.parse_args()

    # If config is relative, resolve it relative to this script
    config_path = args.config
    if not os.path.isabs(config_path):
        config_path = os.path.join(os.path.dirname(__file__), config_path)

    print("=" * 80)
    print("Trajectory Evaluation Tool - LandingPageGenerator-H_A2A")
    print("=" * 80)
    print(f"\nConfig file: {config_path}")

    # Create evaluator
    evaluator = DatasetEvaluator(config_path)

    print(f"Project: {evaluator.project_name}")
    print(f"Reference trajectory: {evaluator.reference_trajectory}")
    print(f"Target tools: {evaluator.target_tools}")
    print(f"Models: {evaluator.models}")

    # Dynamic optimization info
    if evaluator.enable_autogen_pattern_matching:
        print("\nAutoGen dynamic reference optimization: enabled")
        print(
            "   - LLM insertion patterns between tools: enumerate all 0/1 combinations"
        )
        print("   - 1 tool: 1 pattern")
        print("   - 2 tools: 2 patterns (0 or 1 LLM between tools)")
        print("   - 3 tools: 4 patterns")
        print("   - Selection score: exact*3 + in_order*2 + any_order*1")
    else:
        print("\nAutoGen dynamic reference optimization: disabled")

    # Evaluate all models
    df = evaluator.evaluate_all_models(args.base_dir)

    if df.empty:
        print("\nEvaluation failed: no data")
        return

    print("\n" + "=" * 80)
    print("Summary")
    print("=" * 80)

    # Pretty print
    pd.set_option("display.max_columns", None)
    pd.set_option("display.width", None)
    pd.set_option("display.float_format", lambda x: f"{x:.4f}")

    print("\n" + df.to_string(index=False))

    # Save results
    output_dir = os.path.dirname(args.output) or "."
    os.makedirs(output_dir, exist_ok=True)

    if args.format in ["csv", "both", "markdown"]:
        csv_file = args.output
        df.to_csv(csv_file, index=False)
        print(f"\nCSV saved: {csv_file}")

    if args.format in ["markdown", "both"]:
        print("Markdown output is disabled; only CSV will be produced.")

    print("\n" + "=" * 80)
    print("Evaluation completed")
    print("=" * 80)


if __name__ == "__main__":
    main()