File size: 10,845 Bytes
40ee6b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Weights & Biases integration for experiment tracking.
"""

import os
from datetime import datetime
from typing import Any

try:
    import wandb

    WANDB_AVAILABLE = True
except ImportError:
    WANDB_AVAILABLE = False
    wandb = None


class WandBTracker:
    """Weights & Biases experiment tracker for multi-agent MCTS demo."""

    def __init__(self, project_name: str = "langgraph-mcts-demo", entity: str | None = None, enabled: bool = True):
        """Initialize W&B tracker.

        Args:
            project_name: W&B project name
            entity: W&B entity (username or team)
            enabled: Whether tracking is enabled
        """
        self.project_name = project_name
        self.entity = entity
        self.enabled = enabled and WANDB_AVAILABLE
        self.run = None
        self.run_id = None

    def is_available(self) -> bool:
        """Check if W&B is available."""
        return WANDB_AVAILABLE

    def init_run(
        self, run_name: str | None = None, config: dict[str, Any] | None = None, tags: list[str] | None = None
    ) -> bool:
        """Initialize a new W&B run.

        Args:
            run_name: Optional name for the run
            config: Configuration dictionary to log
            tags: Tags for the run

        Returns:
            True if run initialized successfully, False otherwise
        """
        if not self.enabled:
            return False

        try:
            # Generate run name if not provided
            if run_name is None:
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                run_name = f"mcts_query_{timestamp}"

            # Default tags
            if tags is None:
                tags = ["demo", "multi-agent", "mcts"]

            # Initialize run
            self.run = wandb.init(
                project=self.project_name,
                entity=self.entity,
                name=run_name,
                config=config or {},
                tags=tags,
                reinit=True,
            )

            self.run_id = self.run.id
            return True

        except Exception as e:
            print(f"W&B init error: {e}")
            self.enabled = False
            return False

    def log_query_config(self, config: dict[str, Any]):
        """Log query configuration.

        Args:
            config: Configuration dictionary with agent settings, MCTS params, etc.
        """
        if not self.enabled or not self.run:
            return

        try:
            wandb.config.update(config)
        except Exception as e:
            print(f"W&B config log error: {e}")

    def log_agent_result(
        self,
        agent_name: str,
        response: str,
        confidence: float,
        execution_time_ms: float,
        reasoning_steps: list[str] | None = None,
    ):
        """Log individual agent results.

        Args:
            agent_name: Name of the agent (HRM, TRM, MCTS)
            response: Agent's response text
            confidence: Confidence score (0-1)
            execution_time_ms: Execution time in milliseconds
            reasoning_steps: Optional list of reasoning steps
        """
        if not self.enabled or not self.run:
            return

        try:
            metrics = {
                f"{agent_name}/confidence": confidence,
                f"{agent_name}/execution_time_ms": execution_time_ms,
                f"{agent_name}/response_length": len(response),
            }

            if reasoning_steps:
                metrics[f"{agent_name}/num_reasoning_steps"] = len(reasoning_steps)

            wandb.log(metrics)

            # Log response as text
            wandb.log({f"{agent_name}/response": wandb.Html(f"<pre>{response}</pre>")})

        except Exception as e:
            print(f"W&B agent result log error: {e}")

    def log_mcts_result(self, mcts_result: dict[str, Any]):
        """Log MCTS-specific metrics.

        Args:
            mcts_result: Dictionary containing MCTS search results
        """
        if not self.enabled or not self.run:
            return

        try:
            # Extract key metrics
            metrics = {
                "mcts/best_value": mcts_result.get("best_value", 0),
                "mcts/root_visits": mcts_result.get("root_visits", 0),
                "mcts/total_nodes": mcts_result.get("total_nodes", 0),
                "mcts/max_depth": mcts_result.get("max_depth_reached", 0),
                "mcts/iterations": mcts_result.get("iterations_completed", 0),
                "mcts/exploration_weight": mcts_result.get("exploration_weight", 1.414),
            }

            wandb.log(metrics)

            # Log top actions as table
            if "top_actions" in mcts_result:
                top_actions_data = []
                for action in mcts_result["top_actions"]:
                    top_actions_data.append(
                        [
                            action.get("action", ""),
                            action.get("visits", 0),
                            action.get("value", 0),
                            action.get("ucb1", 0),
                        ]
                    )

                if top_actions_data:
                    table = wandb.Table(data=top_actions_data, columns=["Action", "Visits", "Value", "UCB1"])
                    wandb.log({"mcts/top_actions_table": table})

            # Log tree visualization as text artifact
            if "tree_visualization" in mcts_result:
                wandb.log({"mcts/tree_visualization": wandb.Html(f"<pre>{mcts_result['tree_visualization']}</pre>")})

        except Exception as e:
            print(f"W&B MCTS result log error: {e}")

    def log_consensus(self, consensus_score: float, agents_used: list[str], final_response: str):
        """Log consensus metrics.

        Args:
            consensus_score: Agreement score between agents (0-1)
            agents_used: List of agent names that were used
            final_response: Final synthesized response
        """
        if not self.enabled or not self.run:
            return

        try:
            wandb.log(
                {
                    "consensus/score": consensus_score,
                    "consensus/num_agents": len(agents_used),
                    "consensus/agents": ", ".join(agents_used),
                    "consensus/final_response_length": len(final_response),
                }
            )

            # Categorize consensus level
            if consensus_score > 0.7:
                consensus_level = "high"
            elif consensus_score > 0.4:
                consensus_level = "medium"
            else:
                consensus_level = "low"

            wandb.log({"consensus/level": consensus_level})

        except Exception as e:
            print(f"W&B consensus log error: {e}")

    def log_performance(self, total_time_ms: float):
        """Log overall performance metrics.

        Args:
            total_time_ms: Total execution time in milliseconds
        """
        if not self.enabled or not self.run:
            return

        try:
            wandb.log({"performance/total_time_ms": total_time_ms, "performance/total_time_s": total_time_ms / 1000})
        except Exception as e:
            print(f"W&B performance log error: {e}")

    def log_full_result(self, result: dict[str, Any]):
        """Log the complete result as an artifact.

        Args:
            result: Full framework result dictionary
        """
        if not self.enabled or not self.run:
            return

        try:
            # Create artifact
            artifact = wandb.Artifact(name=f"query_result_{self.run_id}", type="result")

            # Add result as JSON
            import json
            import tempfile

            with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
                json.dump(result, f, indent=2, default=str)
                temp_path = f.name

            artifact.add_file(temp_path, name="result.json")
            wandb.log_artifact(artifact)

            # Clean up temp file
            os.unlink(temp_path)

        except Exception as e:
            print(f"W&B full result log error: {e}")

    def log_query_summary(
        self, query: str, use_hrm: bool, use_trm: bool, use_mcts: bool, consensus_score: float, total_time_ms: float
    ):
        """Log a summary row for the query.

        Args:
            query: The input query
            use_hrm: Whether HRM was enabled
            use_trm: Whether TRM was enabled
            use_mcts: Whether MCTS was enabled
            consensus_score: Final consensus score
            total_time_ms: Total execution time
        """
        if not self.enabled or not self.run:
            return

        try:
            # Create summary table entry
            summary_data = [
                [
                    query[:100] + "..." if len(query) > 100 else query,
                    "βœ“" if use_hrm else "βœ—",
                    "βœ“" if use_trm else "βœ—",
                    "βœ“" if use_mcts else "βœ—",
                    f"{consensus_score:.1%}",
                    f"{total_time_ms:.2f}",
                ]
            ]

            table = wandb.Table(data=summary_data, columns=["Query", "HRM", "TRM", "MCTS", "Consensus", "Time (ms)"])

            wandb.log({"query_summary": table})

        except Exception as e:
            print(f"W&B summary log error: {e}")

    def finish_run(self):
        """Finish the current W&B run."""
        if not self.enabled or not self.run:
            return

        try:
            wandb.finish()
            self.run = None
            self.run_id = None
        except Exception as e:
            print(f"W&B finish error: {e}")

    def get_run_url(self) -> str | None:
        """Get the URL for the current run.

        Returns:
            URL string or None if no active run
        """
        if not self.enabled or not self.run:
            return None

        try:
            return self.run.get_url()
        except Exception:
            return None


# Global tracker instance
_global_tracker: WandBTracker | None = None


def get_tracker(
    project_name: str = "langgraph-mcts-demo", entity: str | None = None, enabled: bool = True
) -> WandBTracker:
    """Get or create the global W&B tracker.

    Args:
        project_name: W&B project name
        entity: W&B entity
        enabled: Whether tracking is enabled

    Returns:
        WandBTracker instance
    """
    global _global_tracker

    if _global_tracker is None:
        _global_tracker = WandBTracker(project_name=project_name, entity=entity, enabled=enabled)

    return _global_tracker


def is_wandb_available() -> bool:
    """Check if W&B is available."""
    return WANDB_AVAILABLE