|
|
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: |
|
|
|
|
|
|
|
|
tools_non_error = tools_df[ |
|
|
tools_df["tool"].isin(["tool_name", "TEMP_TOOL"]) == False |
|
|
].copy() |
|
|
|
|
|
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 |
|
|
""" |
|
|
|
|
|
tool_counts = tools_df["tool"].value_counts() |
|
|
|
|
|
|
|
|
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 len(available_samples) < sample_size: |
|
|
available_samples = tool_samples.copy() |
|
|
|
|
|
|
|
|
current_subset = available_samples.sample(n=sample_size, replace=replace) |
|
|
downsampled_sets.append(current_subset) |
|
|
|
|
|
|
|
|
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): |
|
|
|
|
|
n_samples = len(tool_samples) |
|
|
n_additional = sample_size - n_samples |
|
|
|
|
|
|
|
|
additional_samples = tool_samples.sample(n=n_additional, replace=True) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
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: |
|
|
|
|
|
accuracy = compute_subset_accuracy(subset) |
|
|
tool_accuracies.append(accuracy) |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
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] |
|
|
|
|
|
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: |
|
|
|
|
|
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}") |
|
|
|
|
|
tool_data = tools_df[tools_df["tool"] == tool] |
|
|
|
|
|
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 < 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_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_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." |
|
|
) |
|
|
|
|
|
tool_names = list(more_sample_tools.keys()) |
|
|
print(f"Downloaded historical file in tmp folder: {tools_historical_file}") |
|
|
|
|
|
historical_tools_df = pd.read_parquet(TMP_DIR / tools_historical_file) |
|
|
|
|
|
historical_tools_df = historical_tools_df[ |
|
|
historical_tools_df["tool"].isin(tool_names) |
|
|
] |
|
|
|
|
|
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) |
|
|
|
|
|
needed_samples = recent_samples_size - current_count |
|
|
if count < needed_samples: |
|
|
|
|
|
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]}") |
|
|
|
|
|
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") |
|
|
|
|
|
recent_samples = get_recent_samples(historical_tool_data, needed_samples) |
|
|
|
|
|
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) |
|
|
|
|
|
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() |
|
|
|
|
|
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") |
|
|
|
|
|
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) |
|
|
|
|
|
if len(more_sample_tools) > 0: |
|
|
print("Second attempt to complete the population size") |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
update_global_accuracy( |
|
|
valid_tools, tools_df, global_accuracies, sample_size, n_subsets |
|
|
) |
|
|
|
|
|
|
|
|
if len(more_sample_tools) > 0: |
|
|
new_tools.extend(more_sample_tools.keys()) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return global_accuracies, new_tools |
|
|
|
|
|
|
|
|
def compute_global_weekly_accuracy(clean_tools_df): |
|
|
""" |
|
|
Compute accuracy following version 5.0 of spec""" |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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, |
|
|
} |
|
|
|
|
|
|
|
|
report_df = pd.DataFrame([weekly_report]) |
|
|
filename = ROOT_DIR / "weekly_top_3_tools_report.csv" |
|
|
|
|
|
|
|
|
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. |
|
|
""" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
global_accuracies, new_tools = compute_global_weekly_accuracy( |
|
|
clean_tools_df=clean_tools_df |
|
|
) |
|
|
|
|
|
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""" |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
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) |
|
|
|
|
|
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] |
|
|
|
|
|
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 |
|
|
) |
|
|
|
|
|
|
|
|
if len(new_tools) > 0: |
|
|
print(f"Tools with not enough samples: {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: |
|
|
|
|
|
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 |
|
|
|
|
|
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") |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|