Calculate statistics for a single round
(input_file, available_tools=None)
| 58 | |
| 59 | |
| 60 | def single_round_statistics(input_file, available_tools=None): |
| 61 | """Calculate statistics for a single round""" |
| 62 | def avg_statistic(value_list): |
| 63 | if value_list: |
| 64 | return sum(value_list) / len(value_list) |
| 65 | return 0 |
| 66 | |
| 67 | try: |
| 68 | with open(input_file, 'r', encoding='utf-8') as f: |
| 69 | samples = [json.loads(line) for line in f] |
| 70 | except Exception as e: |
| 71 | print(f"Error loading file {input_file}: {e}") |
| 72 | return {} |
| 73 | |
| 74 | num_invalid = 0 |
| 75 | tool_invocation = defaultdict(list) |
| 76 | answer_lengths, traj_lengths = [], [] |
| 77 | |
| 78 | try: |
| 79 | tokenizer = AutoTokenizer.from_pretrained("/path/to/your/Qwen2.5-72B-Instruct") |
| 80 | except Exception as e: |
| 81 | import tiktoken |
| 82 | tokenizer = tiktoken.encoding_for_model("gpt-4o") |
| 83 | |
| 84 | for sample in samples: |
| 85 | msgs = sample.get("messages", []) |
| 86 | final_msg = msgs[-1]["content"] if len(msgs) else "" |
| 87 | |
| 88 | if "<answer>" not in final_msg or "</answer>" not in final_msg: |
| 89 | num_invalid += 1 |
| 90 | answer_length = 0 |
| 91 | else: |
| 92 | answer = final_msg.split("<answer>")[1].split("</answer>")[0].strip() |
| 93 | answer_length = len(tokenizer.encode(answer)) |
| 94 | answer_lengths.append(answer_length) |
| 95 | |
| 96 | cur_tool_invocation = defaultdict(int) |
| 97 | for msg in msgs: |
| 98 | if msg["role"] == "assistant": |
| 99 | try: |
| 100 | tool_call = msg["content"].split("<tool_call>")[1].split("</tool_call>")[0].strip() |
| 101 | tool_call = json.loads(tool_call) |
| 102 | tool_name = tool_call["name"] |
| 103 | if available_tools and tool_name in available_tools: |
| 104 | cur_tool_invocation[tool_name] += 1 |
| 105 | else: |
| 106 | cur_tool_invocation["invalid"] += 1 |
| 107 | cur_tool_invocation["total"] += 1 |
| 108 | except: |
| 109 | continue |
| 110 | |
| 111 | for k, v in cur_tool_invocation.items(): |
| 112 | tool_invocation[k].append(v) |
| 113 | |
| 114 | traj_length = len(tokenizer.encode("".join(msg["content"] for msg in msgs))) |
| 115 | traj_lengths.append(traj_length) |
| 116 | |
| 117 | metrics = { |
no test coverage detected