File size: 29,575 Bytes
cd451ea
 
471986c
cd451ea
 
 
 
599eb7e
 
 
 
 
 
471986c
807709a
66dc719
cd451ea
 
 
9bb36bd
599eb7e
471986c
 
807709a
 
9bb36bd
 
 
 
 
 
 
cd451ea
 
471986c
 
 
 
 
 
 
807709a
471986c
 
 
 
 
 
 
cd451ea
 
 
 
 
 
 
 
 
 
 
471986c
 
 
599eb7e
 
 
471986c
807709a
 
 
471986c
 
 
 
 
 
807709a
471986c
 
 
 
 
807709a
599eb7e
 
 
471986c
807709a
 
599eb7e
 
 
471986c
 
807709a
471986c
 
 
599eb7e
471986c
 
 
 
 
 
 
 
 
 
 
 
 
599eb7e
 
 
 
471986c
 
 
 
 
 
 
 
 
 
599eb7e
471986c
 
 
 
 
 
 
 
599eb7e
 
 
807709a
 
 
 
 
 
 
 
 
 
599eb7e
807709a
599eb7e
807709a
599eb7e
807709a
 
471986c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd451ea
471986c
 
 
 
 
 
 
 
 
 
 
 
 
b1f5e34
471986c
b1f5e34
471986c
b1f5e34
471986c
 
 
807709a
471986c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
599eb7e
471986c
 
 
 
807709a
 
 
 
 
599eb7e
807709a
 
 
 
 
 
 
599eb7e
807709a
599eb7e
 
807709a
 
 
 
 
 
 
599eb7e
 
 
 
 
 
 
 
807709a
599eb7e
 
807709a
599eb7e
807709a
 
 
 
 
599eb7e
 
 
 
 
 
 
 
807709a
 
9bb36bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
599eb7e
807709a
 
 
599eb7e
807709a
599eb7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
807709a
599eb7e
807709a
599eb7e
 
 
 
 
 
807709a
599eb7e
 
 
 
 
 
 
 
 
 
 
9bb36bd
599eb7e
 
 
 
 
 
 
807709a
 
9bb36bd
 
 
807709a
599eb7e
807709a
 
599eb7e
 
 
9bb36bd
599eb7e
 
746d43a
599eb7e
 
 
746d43a
 
599eb7e
746d43a
599eb7e
746d43a
599eb7e
9bb36bd
599eb7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bb36bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
746d43a
471986c
 
9bb36bd
 
 
 
 
7bea63a
9bb36bd
 
7bea63a
 
 
 
9bb36bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bea63a
9bb36bd
 
 
 
 
 
7bea63a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bb36bd
 
471986c
 
 
599eb7e
471986c
9bb36bd
 
 
 
 
746d43a
471986c
 
 
 
 
 
599eb7e
7bea63a
471986c
 
 
 
cd451ea
 
 
471986c
cd451ea
 
 
 
 
 
746d43a
d7c2876
 
 
 
 
 
 
 
 
599eb7e
 
cd451ea
 
 
 
 
 
f3d7989
 
cd451ea
599eb7e
cd451ea
 
 
 
807709a
599eb7e
9bb36bd
 
cd451ea
9bb36bd
599eb7e
 
807709a
 
 
 
9bb36bd
cd451ea
 
 
 
 
 
599eb7e
 
7bea63a
599eb7e
 
 
 
 
 
 
 
7bea63a
599eb7e
 
 
 
 
 
807709a
 
 
599eb7e
807709a
 
 
 
 
 
599eb7e
 
 
 
 
 
 
807709a
599eb7e
 
 
 
 
 
 
cd451ea
 
 
807709a
7bea63a
599eb7e
 
cd451ea
599eb7e
 
 
 
 
cd451ea
 
 
9bb36bd
 
 
cd451ea
 
9bb36bd
 
cd451ea
9bb36bd
c51b070
 
792d89e
9bb36bd
 
 
 
 
cd451ea
9bb36bd
180a869
cd451ea
9bb36bd
b6b1f39
 
180a869
b6b1f39
cd451ea
180a869
cd451ea
b6b1f39
cd451ea
 
 
180a869
 
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
import os
import pandas as pd
from typing import Tuple, List, Dict
import ipfshttpclient
from utils import INC_TOOLS
from typing import List
from utils import TMP_DIR, ROOT_DIR
from cloud_storage import (
    initialize_client,
    download_tools_historical_files,
    FILES_IN_TWO_MONTHS,
    FILES_IN_FOUR_MONTHS,
)
import math
import time

ACCURACY_FILENAME = "tools_accuracy.csv"
IPFS_SERVER = "/dns/registry.autonolas.tech/tcp/443/https"
GCP_IPFS_SERVER = "/dns/registry.gcp.autonolas.tech/tcp/443/https"
SAMPLING_POPULATION_SIZE = 500
RECENTS_SAMPLES_SIZE = 5000
NR_SUBSETS = 100
SAMPLES_THRESHOLD = 50
DEFAULT_ACCURACY = 51.0
LAST_MODEL_UPDATE = "2025-06-03"
CLAUDE_TOOLS = [
    "claude-prediction-online",
    "claude-prediction-offline",
    "prediction-request-rag-claude",
    "prediction-request-reasoning-claude",
    "prediction-url-cot-claude",
]


def mean_and_std(numbers):
    mean = sum(numbers) / len(numbers)
    squared_diff_sum = sum((x - mean) ** 2 for x in numbers)
    std_dev = math.sqrt(squared_diff_sum / len(numbers))
    return mean, std_dev


def clean_tools_dataset(tools_df: pd.DataFrame) -> pd.DataFrame:

    # Remove tool_name and TEMP_TOOL
    tools_non_error = tools_df[
        tools_df["tool"].isin(["tool_name", "TEMP_TOOL"]) == False
    ].copy()
    # Remove errors
    tools_non_error = tools_non_error[tools_non_error["error"] == 0]
    tools_non_error.loc[:, "currentAnswer"] = tools_non_error["currentAnswer"].replace(
        {"no": "No", "yes": "Yes"}
    )
    tools_non_error = tools_non_error[
        tools_non_error["currentAnswer"].isin(["Yes", "No"])
    ]
    tools_non_error = tools_non_error[tools_non_error["vote"].isin(["Yes", "No"])]
    tools_non_error["win"] = (
        tools_non_error["currentAnswer"] == tools_non_error["vote"]
    ).astype(int)
    tools_non_error.columns = tools_non_error.columns.astype(str)
    return tools_non_error


def classify_tools(
    tools_df: pd.DataFrame, recent_samples_size: int
) -> Tuple[Dict, Dict, Dict]:
    """
    Separates tools into different groups based on two use-cases:
    1. Tools with enough samples to reach sample_size
    2. Tools with not enough samples to reach sample_size

    Args:
        tools_df: DataFrame containing the tools data
        sample_size: Target number of samples for each tool

    Returns:
        Tuple of two dictionaries containing tools that are from group 1 and group 2
    """
    # Get count of samples per tool
    tool_counts = tools_df["tool"].value_counts()

    # Separate tools based on sample size
    valid_tools = {
        tool: count
        for tool, count in tool_counts.items()
        if count >= recent_samples_size
    }

    more_samples_tools = {
        tool: count
        for tool, count in tool_counts.items()
        if count < recent_samples_size
    }

    return valid_tools, more_samples_tools


def downsample_tool_multiple(
    tool_samples: pd.DataFrame, sample_size: int, n_subsets: int, replace: bool = False
) -> List[pd.DataFrame]:
    """
    Creates multiple downsampled subsets from the tool samples

    Args:
        tool_samples: DataFrame containing samples for a specific tool
        sample_size: Number of samples to select for each subset
        n_subsets: Number of subsets to create

    Returns:
        List of DataFrames containing the downsampled subsets
    """
    total_samples = len(tool_samples)
    if total_samples < RECENTS_SAMPLES_SIZE:
        raise ValueError(
            f"Not enough samples available: {total_samples} < {RECENTS_SAMPLES_SIZE}"
        )
    print(f"total samples available: {total_samples}")
    downsampled_sets = []
    available_samples = tool_samples.copy()
    available_samples.set_index("request_id", inplace=True, drop=False)
    for i in range(n_subsets):
        # If we don't have enough samples left, reset the available samples
        if len(available_samples) < sample_size:
            available_samples = tool_samples.copy()

        # Sample without replacement from available samples
        current_subset = available_samples.sample(n=sample_size, replace=replace)
        downsampled_sets.append(current_subset)

        # Remove used samples from available pool
        available_samples = available_samples.drop(current_subset.index)

    return downsampled_sets


def get_recent_samples(
    tool_samples: pd.DataFrame, recent_samples_size: int
) -> pd.DataFrame:
    """
    Gets the most recent samples from the tool samples

    Args:
        tool_samples: DataFrame containing samples for a specific tool
        sample_size: Number of samples to select

    Returns:
        DataFrame containing the most recent samples
    """
    if len(tool_samples) < recent_samples_size:
        raise ValueError(
            f"Not enough samples available: {len(tool_samples)} < {recent_samples_size}"
        )
    return tool_samples.nlargest(recent_samples_size, "request_time")


def upsample_tool_multiple(
    tool_samples: pd.DataFrame, sample_size: int, n_subsets: int
) -> List[pd.DataFrame]:
    """
    Creates multiple upsampled subsets from the tool samples

    Args:
        tool_samples: DataFrame containing samples for a specific tool
        sample_size: Target number of samples for each subset
        n_subsets: Number of subsets to create

    Returns:
        List of DataFrames containing the upsampled subsets
    """
    upsampled_sets = []

    for _ in range(n_subsets):
        # Calculate how many additional samples we need
        n_samples = len(tool_samples)
        n_additional = sample_size - n_samples

        # Get additional samples
        additional_samples = tool_samples.sample(n=n_additional, replace=True)

        # Combine original and additional samples
        upsampled_set = pd.concat([tool_samples, additional_samples])
        upsampled_sets.append(upsampled_set)

    return upsampled_sets


def compute_subset_accuracy(tools_subset: pd.DataFrame) -> float:
    """
    Computes the accuracy of a subset of tools.

    Args:
        tools_subset: DataFrame containing a subset of tools

    Returns:
        Accuracy of the subset
    """

    wins = tools_subset["win"].value_counts().reindex([0, 1], fill_value=0)
    # Ensure both 0 and 1 columns exist
    if 0 not in wins.index:
        wins[0] = 0
    if 1 not in wins.index:
        wins[1] = 0
    return (wins[1] / (wins[0] + wins[1])) * 100


def compute_tool_estimated_accuracy(subset_list: List[pd.DataFrame]) -> Tuple:
    """
    Computes the accuracy for the tool averaging the accuracy achieved within the list of subsets.

    Args:
        subset_list: List of DataFrames containing subsets of the same tool

    Returns:
        float with the average accuracy of the tool across all subsets
    """
    tool_accuracies = []
    for subset in subset_list:
        # only one tool per subset, all
        accuracy = compute_subset_accuracy(subset)
        tool_accuracies.append(accuracy)

    # print(f"tool accuracies: {tool_accuracies}")
    accuracy_mean, accuracy_std = mean_and_std(tool_accuracies)
    return accuracy_mean, accuracy_std


def update_global_accuracy(
    valid_tools: Dict,
    tools_df: pd.DataFrame,
    global_accuracies: Dict,
    sample_size: int,
    nr_subsets: int = NR_SUBSETS,
    one_tool: str = None,
) -> Dict:
    """
    Updates the global accuracies for tools that have enough samples.

    Args:
        valid_tools: Dictionary of tools with enough samples
        tools_df: DataFrame containing the tools data
        global_accuracies: Dictionary to store global accuracies
        sample_size: Target number of samples for each subset
        nr_subsets: Number of subsets to create
        one_tool: Optional specific tool to compute accuracy for

    Returns:
        Updated global accuracies dictionary
    """
    if one_tool:
        print(f"Computing accuracy for tool: {one_tool}")
        tool_samples = tools_df[tools_df["tool"] == one_tool].copy()
        # recent_samples = get_recent_samples(tool_samples, RECENTS_SAMPLES_SIZE)

        downsampled_sets = downsample_tool_multiple(
            tool_samples, sample_size, nr_subsets
        )

        tool_mean_accuracy, tool_std = compute_tool_estimated_accuracy(downsampled_sets)
        global_accuracies[one_tool] = {
            "mean": float(tool_mean_accuracy),
            "std": tool_std,
        }

        return global_accuracies

    for tool in valid_tools.keys():
        print(f"Processing tool: {tool}")
        tool_samples = tools_df[tools_df["tool"] == tool]
        # recent_samples = get_recent_samples(tool_samples, RECENTS_SAMPLES_SIZE)
        downsampled_sets = downsample_tool_multiple(
            tool_samples, sample_size, nr_subsets
        )
        tool_mean_accuracy, tool_std = compute_tool_estimated_accuracy(downsampled_sets)
        global_accuracies[tool] = {"mean": float(tool_mean_accuracy), "std": tool_std}

    return global_accuracies


def check_upgrade_dates(
    tools_df,
    tools_list,
    new_tools,
    claude_upgrade_date="30-07-2025",
    gpt_upgrade_date="03-06-2025",
) -> None:
    # Convert upgrade dates to datetime
    claude_upgrade_date = pd.to_datetime(claude_upgrade_date, format="%d-%m-%Y").date()
    gpt_upgrade_date = pd.to_datetime(gpt_upgrade_date, format="%d-%m-%Y").date()
    for tool in tools_list.keys():
        print(f"checking tool {tool}")
        # take the RECENT_SAMPLES from tools_df
        tool_data = tools_df[tools_df["tool"] == tool]
        # sort tool_data by request date in ascending order
        tool_data = tool_data.sort_values(by="request_date", ascending=True)
        if len(tool_data) < RECENTS_SAMPLES_SIZE:
            new_tools.append(tool)
            continue
        recent_samples = get_recent_samples(
            tool_data, recent_samples_size=RECENTS_SAMPLES_SIZE
        )
        recent_samples = recent_samples.sort_values(by="request_date", ascending=True)
        print(recent_samples.head())
        oldest_sample_date = recent_samples.iloc[0].request_date
        if isinstance(oldest_sample_date, str):
            oldest_sample_date = pd.to_datetime(oldest_sample_date).date()
        print(f"tool {tool}: oldest sample date {oldest_sample_date}")
        if tool in CLAUDE_TOOLS:
            # if oldest_sample_date is before claude_upgrade_date then remove the tool
            # from valid_tools and add it to the list of other_tools
            if oldest_sample_date < claude_upgrade_date:
                print(f"the oldest sample found is older than {claude_upgrade_date}")
                new_tools.append(tool)
        elif oldest_sample_date < gpt_upgrade_date:
            print(f"the oldest sample found is older than {gpt_upgrade_date}")
            new_tools.append(tool)
    return


def check_upgraded_tools(
    tools_df,
    valid_tools,
    other_tools,
):
    """
    Function to update the input lists and remove from valid tools any tools whose oldest date is before the upgrade dates
    """
    new_tools = []
    # Check and remove tools from valid_tools
    check_upgrade_dates(tools_df, valid_tools, new_tools)
    for tool in new_tools:
        if tool in valid_tools.keys():
            print(f"removing tool {tool} from valid tools")
            del valid_tools[tool]
    # Check and remove tools from other_tools
    check_upgrade_dates(tools_df, other_tools, new_tools)
    for tool in new_tools:
        if tool in other_tools.keys():
            print(f"removing tool {tool} from other tools")
            del other_tools[tool]
    return new_tools


def add_historical_data(
    tools_historical_file: str,
    tools_df: pd.DataFrame,
    more_sample_tools: Dict,
    recent_samples_size: int,
    valid_tools: Dict,
    completed_tools: List[str],
) -> pd.DataFrame:
    """
    It searches into the historical cloud files to get more samples for the tools in more_sample_tools.
    """
    if not tools_historical_file:
        raise ValueError(
            "No historical tools file found, skipping adding historical data."
        )
    # get the historical tools data
    tool_names = list(more_sample_tools.keys())
    print(f"Downloaded historical file in tmp folder: {tools_historical_file}")
    # Load the historical tools data
    historical_tools_df = pd.read_parquet(TMP_DIR / tools_historical_file)
    # check if the historical tools data has samples from the tools that need more samples
    historical_tools_df = historical_tools_df[
        historical_tools_df["tool"].isin(tool_names)
    ]
    # check the volume of samples for the tools in the historical data
    historical_tool_counts = historical_tools_df["tool"].value_counts()
    for tool, count in historical_tool_counts.items():
        historical_tool_data = historical_tools_df[historical_tools_df["tool"] == tool]
        current_count = more_sample_tools.get(tool, 0)
        # compute the minimal amount of needed samples
        needed_samples = recent_samples_size - current_count
        if count < needed_samples:
            # update the count in more_sample_tools but do not remove the tool
            print(
                f"Tool {tool} has not enough samples in historical data: {count} < {needed_samples}"
            )
            more_sample_tools[tool] = current_count + count
            print(f"updated count for tool {tool}: {more_sample_tools[tool]}")
            # Combine the current tools with the historical data for that tool
            tools_df = pd.concat([tools_df, historical_tool_data], ignore_index=True)
            continue

        print(f"Tool {tool} has enough samples now:. Adding {needed_samples} samples")
        # take only the latest needed_samples in historical_tool_data
        recent_samples = get_recent_samples(historical_tool_data, needed_samples)
        # Combine the current tools with the historical ones
        tools_df = pd.concat([tools_df, recent_samples], ignore_index=True)
        tools_df = tools_df.sort_values(by="request_date", ascending=True)
        valid_tools[tool] = count + needed_samples
        completed_tools.append(tool)
        # Remove the tool from more_sample_tools
        if tool in more_sample_tools:
            print(f"Deleting tool {tool} from more_sample_tools")
            del more_sample_tools[tool]
    return tools_df


def check_historical_samples(
    global_accuracies, more_sample_tools, valid_tools, sample_size, n_subsets
):
    client = initialize_client()
    # first attempt: historical file download
    tool_names = list(more_sample_tools.keys())
    print(f"Tools with not enough samples: {tool_names}")
    completed_tools = []
    if len(tool_names) > 0:
        print("First attempt to complete the population size")
        # first attempt: historical file from 4 months ago
        tools_historical_file = download_tools_historical_files(
            client, skip_files_count=FILES_IN_TWO_MONTHS
        )

        tools_df = add_historical_data(
            tools_historical_file,
            tools_df,
            more_sample_tools,
            RECENTS_SAMPLES_SIZE,
            valid_tools,
            completed_tools,
        )
        print(more_sample_tools)
        # second attempt: historical file from 6 months ago
        if len(more_sample_tools) > 0:
            print("Second attempt to complete the population size")
            # second historical file download
            tools_historical_file2 = download_tools_historical_files(
                client,
                skip_files_count=FILES_IN_FOUR_MONTHS,
            )

            tools_df = add_historical_data(
                tools_historical_file2,
                tools_df,
                more_sample_tools,
                RECENTS_SAMPLES_SIZE,
                valid_tools,
                completed_tools,
            )
            print(more_sample_tools)
    if len(completed_tools) > 0:
        for tool in completed_tools:
            update_global_accuracy(
                valid_tools,
                tools_df,
                global_accuracies,
                sample_size,
                n_subsets,
                one_tool=tool,
            )
    return


def compute_global_accuracy_same_population(
    tools_df: pd.DataFrame,
    recent_samples_size: int = RECENTS_SAMPLES_SIZE,
    sample_size: int = SAMPLING_POPULATION_SIZE,
    n_subsets: int = NR_SUBSETS,
) -> Tuple[Dict, Dict]:
    """
    For the tools in the dataset, it creates different subsets of the same size (using downsampling or upsampling) and
    computes the accuracy for each subset. Finally it averages the accuracies across all subsets.

    Args:
        tools_df: DataFrame containing the tools data
        sample_size: Target number of samples per tool
        n_subsets: Number of balanced datasets to create

    Returns:
        List of global accuracies for the tools
    """

    valid_tools, more_sample_tools = classify_tools(tools_df, recent_samples_size)
    # check tools that were upgraded recently
    # otherwise they will be moved as new_tools
    new_tools = check_upgraded_tools(tools_df, valid_tools, more_sample_tools)
    print(f"new tools {new_tools} after checking the upgraded tools")
    global_accuracies = {}
    if len(valid_tools) > 0:
        # Compute the accuracy for tools in valid_tools
        update_global_accuracy(
            valid_tools, tools_df, global_accuracies, sample_size, n_subsets
        )

    # Check historical files for tools that need more samples
    if len(more_sample_tools) > 0:
        new_tools.extend(more_sample_tools.keys())
        # check_historical_samples(
        #     global_accuracies, more_sample_tools, valid_tools, sample_size, n_subsets
        # )
        # for tool in more_sample_tools.keys():
        #     # tool but not reaching yet the population size so treated as a new tool
        #     new_tools.append(tool)
    return global_accuracies, new_tools


def compute_global_weekly_accuracy(clean_tools_df):
    """
    Compute accuracy following version 5.0 of spec"""
    # get the information in clean_tools_df from last two weeks only, timestamp column is request_time

    three_weeks_ago = pd.Timestamp.now(tz="UTC") - pd.Timedelta(days=7)
    recent_df = clean_tools_df[clean_tools_df["request_time"] >= three_weeks_ago]

    daily_requests = recent_df.groupby(clean_tools_df["request_time"].dt.date)["request_id"].count()
    print("\nDaily request counts:")
    print(daily_requests)

    # compute at the tool level (using "tool" column) the volume of requests per tool
    tool_volumes = (
        recent_df.groupby("tool")["request_id"].count().reset_index(name="volume")
    )
    min_volume = tool_volumes["volume"].min()
    max_volume = tool_volumes["volume"].max()

    # compute the average volume of tool requests in the last two weeks, excluding min and max
    filtered_volumes = tool_volumes[
        (tool_volumes["volume"] != min_volume) & (tool_volumes["volume"] != max_volume)
    ]
    avg_volume = filtered_volumes["volume"].mean()

    print("Tool volumes in last three weeks:")
    print(tool_volumes)
    print(
        f"Average volume of tool requests in last three weeks excluding min and max: {avg_volume}"
    )
    sampling_size = int(avg_volume / 2)
    print(f"Sampling size = {sampling_size}")

    global_accuracies, new_tools = compute_global_accuracy_same_population(
        tools_df=recent_df,
        recent_samples_size=avg_volume,
        sample_size=sampling_size,
        n_subsets=50,
    )

    def save_weekly_top_3_metric(recent_df):
        """Save weekly top 3 tools percentage metric"""
        
        tool_volumes = (
            recent_df.groupby("tool")["request_id"].count().reset_index(name="volume")
        )
        
        global_accuracies, _ = compute_global_accuracy_same_population(
            tools_df=recent_df,
            recent_samples_size=len(recent_df) // len(recent_df['tool'].unique()) if len(recent_df) > 0 else 1000,
            sample_size=sampling_size,
            n_subsets=50
        )
        
        tools_data = []
        for _, row in tool_volumes.iterrows():
            tool = row['tool']
            volume = row['volume']
            accuracy = global_accuracies.get(tool, {}).get('mean', 0)
            tools_data.append({
                'tool': tool,
                'volume': volume,
                'accuracy': accuracy
            })
        
        tools_df = pd.DataFrame(tools_data)
        
        # sort by accuracy descending and get top 3
        top_3_tools = tools_df.nlargest(3, 'accuracy')
        
        top_3_requests = top_3_tools['volume'].sum()
        total_requests = tools_df['volume'].sum()
        top_3_percentage = (top_3_requests / total_requests) * 100 if total_requests > 0 else 0
        
        # Create weekly report
        weekly_report = {
            'timestamp': pd.Timestamp.now(tz="UTC").strftime("%Y-%m-%d %H:%M:%S"),
            'calculation_period': '3_weeks',
            'top_3_percentage': round(top_3_percentage, 2),
            'total_requests': int(total_requests),
            'top_3_total_requests': int(top_3_requests),
            'top_1_tool': top_3_tools.iloc[0]['tool'] if len(top_3_tools) > 0 else None,
            'top_1_accuracy': round(top_3_tools.iloc[0]['accuracy'], 2) if len(top_3_tools) > 0 else None,
            'top_1_volume': int(top_3_tools.iloc[0]['volume']) if len(top_3_tools) > 0 else None,
            'top_2_tool': top_3_tools.iloc[1]['tool'] if len(top_3_tools) > 1 else None,
            'top_2_accuracy': round(top_3_tools.iloc[1]['accuracy'], 2) if len(top_3_tools) > 1 else None,
            'top_2_volume': int(top_3_tools.iloc[1]['volume']) if len(top_3_tools) > 1 else None,
            'top_3_tool': top_3_tools.iloc[2]['tool'] if len(top_3_tools) > 2 else None,
            'top_3_accuracy': round(top_3_tools.iloc[2]['accuracy'], 2) if len(top_3_tools) > 2 else None,
            'top_3_volume': int(top_3_tools.iloc[2]['volume']) if len(top_3_tools) > 2 else None,
        }
        
        # Save to CSV
        report_df = pd.DataFrame([weekly_report])
        filename = ROOT_DIR / "weekly_top_3_tools_report.csv"
        
        # Append to existing file or create new one
        if os.path.exists(filename):
            existing_df = pd.read_csv(filename)
            combined_df = pd.concat([existing_df, report_df], ignore_index=True)
            combined_df.to_csv(filename, index=False)
        else:
            report_df.to_csv(filename, index=False)
        
        print(f"Weekly top 3 tools report saved: {top_3_percentage:.2f}% requests served by top 3 most accurate tools")
        print(f"Report saved to: {filename}")
        
        return weekly_report

    save_weekly_top_3_metric(recent_df)

    return global_accuracies, new_tools


def get_accuracy_info(clean_tools_df: pd.DataFrame) -> [pd.DataFrame, bool, List]:
    """
    Extracts accuracy information from the tools DataFrame.
    """

    # compute global accuracy information for the tools
    # global_accuracies, new_tools = compute_global_accuracy_same_population(
    #     tools_df=clean_tools_df,
    # )
    global_accuracies, new_tools = compute_global_weekly_accuracy(
        clean_tools_df=clean_tools_df
    )
    # transform the dictionary global_accuracies into a DataFrame
    wins = pd.DataFrame(
        [
            {
                "tool": tool,
                "tool_accuracy": global_accuracies[tool]["mean"],
                "std_accuracy": global_accuracies[tool]["std"],
                "nr_responses": SAMPLING_POPULATION_SIZE,
            }
            for tool in global_accuracies.keys()
        ]
    )

    no_timeline_info = False
    try:
        timeline = clean_tools_df.groupby(["tool"])["request_time"].agg(["min", "max"])
        print(timeline.head())
        acc_info = wins.merge(timeline, how="left", on="tool")
    except:
        print("NO REQUEST TIME INFORMATION AVAILABLE")
        no_timeline_info = True
        acc_info = wins
    return acc_info, no_timeline_info, new_tools


def update_tools_accuracy_same_model(
    tools_acc: pd.DataFrame, tools_df: pd.DataFrame, inc_tools: List[str]
) -> pd.DataFrame:
    """To compute/update the latest accuracy information for the different mech tools"""

    # computation of the accuracy information
    tools_inc = tools_df[tools_df["tool"].isin(inc_tools)]
    clean_tools_df = clean_tools_dataset(tools_inc)
    acc_info, no_timeline_info, new_tools = get_accuracy_info(clean_tools_df)

    if tools_acc is None:
        print("Creating accuracy file for the first time")
        return acc_info

    # update the old information
    print(f"accuracy information: {acc_info.head()}")

    tools_to_update = list(acc_info["tool"].values)
    print(f"Tools to update: {tools_to_update}")
    existing_tools = list(tools_acc["tool"].values)
    # dt.strftime("%Y-%m-%d %H:%M:%S")
    acc_info["min"] = acc_info["min"].dt.strftime("%Y-%m-%d %H:%M:%S")
    acc_info["max"] = acc_info["max"].dt.strftime("%Y-%m-%d %H:%M:%S")
    all_accuracies = []
    final_acc_df = pd.DataFrame(columns=tools_acc.columns)
    # accuracy has been computed over the same population size
    new_volume = SAMPLING_POPULATION_SIZE
    for tool in tools_to_update:
        if tool in new_tools or tool not in existing_tools:
            new_tools.append(tool)
            continue
        new_accuracy = round(
            acc_info[acc_info["tool"] == tool]["tool_accuracy"].values[0], 2
        )
        all_accuracies.append(new_accuracy)

        if no_timeline_info:
            new_min_timeline = None
            new_max_timeline = None
        else:
            new_min_timeline = acc_info[acc_info["tool"] == tool]["min"].values[0]
            new_max_timeline = acc_info[acc_info["tool"] == tool]["max"].values[0]

        old_accuracy = tools_acc[tools_acc["tool"] == tool]["tool_accuracy"].values[0]
        old_volume = tools_acc[tools_acc["tool"] == tool]["nr_responses"].values[0]
        # update the accuracy information
        print(f"Updating tool {tool} with new accuracy {new_accuracy}")
        print(f"Old volume: {old_volume}, New volume: {new_volume}")
        print(f"Old accuracy: {old_accuracy}, New accuracy: {new_accuracy}")

        new_row = {
            "tool": tool,
            "tool_accuracy": new_accuracy,
            "nr_responses": SAMPLING_POPULATION_SIZE,
            "min": new_min_timeline,
            "max": new_max_timeline,
        }
        final_acc_df = pd.concat(
            [final_acc_df, pd.DataFrame([new_row])], ignore_index=True
        )

    # compute the average accuracy for the existing tools
    if len(new_tools) > 0:
        print(f"Tools with not enough samples: {new_tools}")
        # compute the average accuracy for the new tools
        avg_accuracy = (
            round(sum(all_accuracies) / len(all_accuracies), 2)
            if len(all_accuracies) > 0
            else DEFAULT_ACCURACY
        )
        timeline = (
            clean_tools_df.groupby(["tool"])["request_time"]
            .agg(["min", "max"])
            .reset_index()
        )
        print(f"Updating with average accuracy: {avg_accuracy}")
        print(f"Timeline: {timeline}")
        for tool in new_tools:
            # timeline info?
            try:
                new_min_timeline = timeline[timeline["tool"] == tool]["min"].values[0]
                new_max_timeline = timeline[timeline["tool"] == tool]["max"].values[0]
            except:
                new_min_timeline = None
                new_max_timeline = None
            # tool,tool_accuracy,total_requests,min,max
            new_row = {
                "tool": tool,
                "tool_accuracy": avg_accuracy,
                "nr_responses": SAMPLING_POPULATION_SIZE,
                "min": new_min_timeline,
                "max": new_max_timeline,
            }
            final_acc_df = pd.concat(
                [final_acc_df, pd.DataFrame([new_row])], ignore_index=True
            )
    print(final_acc_df)
    return final_acc_df


def compute_tools_accuracy():
    """To compute/update the latest accuracy information. Relevant dates
    -- 3rd of June 2025 when the gpt 4.1 update happened
    -- 30th of July 2025 when the Claude 4 update happened"""
    print("Computing accuracy of tools")
    print("Reading tools parquet file")
    tools_df = pd.read_parquet(TMP_DIR / "tools.parquet")

    # Check if the file exists
    acc_data = None
    if os.path.exists(ROOT_DIR / ACCURACY_FILENAME):
        acc_data = pd.read_csv(ROOT_DIR / ACCURACY_FILENAME)

    tools_df["request_time"] = pd.to_datetime(tools_df["request_time"])
    tools_df["request_date"] = tools_df["request_time"].dt.date
    tools_df["request_date"] = pd.to_datetime(tools_df["request_date"])
    tools_df["request_date"] = tools_df["request_date"].dt.strftime("%Y-%m-%d")
    new_acc_data = update_tools_accuracy_same_model(acc_data, tools_df, INC_TOOLS)

    print("Saving into a csv file")
    new_acc_data.to_csv(ROOT_DIR / ACCURACY_FILENAME, index=False)
    # save the data into IPFS
    # push_csv_file_to_ipfs()


def push_csv_file_to_ipfs(filename: str = ACCURACY_FILENAME) -> str:
    """Push the tools accuracy CSV file to IPFS."""
    client = ipfshttpclient.connect(IPFS_SERVER)
    result = client.add(ROOT_DIR / filename)
    print(f"HASH of the tools accuracy file: {result['Hash']}")
    return result["Hash"]


if __name__ == "__main__":
    compute_tools_accuracy()
    # push_csv_file_to_ipfs()