You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

custom_tabulate.py 8.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import os
  2. import sys
  3. import re
  4. from agbench.tabulate_cmd import default_tabulate
  5. import json
  6. import pandas as pd
  7. import sqlite3
  8. import glob
  9. import numpy as np
  10. sys.path.append(os.path.dirname(__file__))
  11. from assistantbench_evaluator import question_scorer
  12. EXCLUDE_DIR_NAMES = ["__pycache__"]
  13. def normalize_answer(a):
  14. # Lower case
  15. # Trim (left and right)
  16. # standardize comma separated values
  17. # Replace multiple spaces with one space
  18. # Remove trailing punctuation
  19. norm_answer = ", ".join(a.strip().lower().split(","))
  20. norm_answer = re.sub(r"[\.\!\?]+$", "", re.sub(r"\s+", " ", norm_answer))
  21. return norm_answer
  22. def scorer(instance_dir):
  23. # Read the expected answer
  24. expected_answer_file = os.path.join(instance_dir, "expected_answer.txt")
  25. if not os.path.isfile(expected_answer_file):
  26. return None
  27. expected_answer = None
  28. with open(expected_answer_file, "rt") as fh:
  29. expected_answer = fh.read().strip()
  30. # Read the console
  31. console_log_file = os.path.join(instance_dir, "console_log.txt")
  32. if not os.path.isfile(console_log_file):
  33. return None
  34. console_log = ""
  35. with open(console_log_file, "rt") as fh:
  36. console_log = fh.read()
  37. final_answer = None
  38. m = re.search(r"FINAL ANSWER:(.*?)\n", console_log, re.DOTALL)
  39. if m:
  40. final_answer = m.group(1).strip()
  41. # Missing the final answer line
  42. if final_answer is None:
  43. return None
  44. # get accuracy from assistantbench util, no normalization done for accuracy
  45. accuracy = question_scorer(final_answer, expected_answer)
  46. n_ex = normalize_answer(expected_answer)
  47. n_final = normalize_answer(final_answer)
  48. return (accuracy, n_ex, n_final)
  49. def get_number_of_chat_messages(chat_messages_dir):
  50. result = 0
  51. for file in glob.glob(f"{chat_messages_dir}/*_messages.json"):
  52. with open(file, "r") as f:
  53. content = json.load(f)
  54. for agent, messages in content.items():
  55. result += len(messages)
  56. return result
  57. def main(args):
  58. parsed_args, all_results = default_tabulate(args, scorer=scorer)
  59. excel_path = parsed_args.excel
  60. if excel_path:
  61. excel_dir = os.path.dirname(excel_path) or "."
  62. if not os.path.exists(excel_dir):
  63. os.makedirs(excel_dir, exist_ok=True)
  64. if not excel_path.endswith((".xlsx", ".xls")):
  65. excel_path += ".xlsx"
  66. runlogs = (
  67. parsed_args.runlogs
  68. if parsed_args.runlogs.endswith("/")
  69. else parsed_args.runlogs + "/"
  70. )
  71. if os.path.isdir(runlogs):
  72. task_ids = sorted(
  73. [
  74. task_id
  75. for task_id in os.listdir(runlogs)
  76. if task_id not in EXCLUDE_DIR_NAMES
  77. ],
  78. key=lambda s: os.path.getmtime(os.path.join(parsed_args.runlogs, s)),
  79. )
  80. else:
  81. raise ValueError("please input a valid directory to tabulate result")
  82. trials = (
  83. sorted(os.listdir(f"{runlogs}{task_ids[0]}"), key=lambda x: int(x))
  84. if len(task_ids) > 0
  85. else []
  86. )
  87. dbnames = [
  88. [f"{runlogs}{task_id}/{trial}/telemetry.db" for task_id in task_ids]
  89. for trial in trials
  90. ]
  91. query = """
  92. SELECT cost, session_id, response, start_time, end_time
  93. FROM (
  94. SELECT invocation_id, cost, session_id, response, start_time, end_time,
  95. ROW_NUMBER() OVER (PARTITION BY invocation_id ORDER BY start_time) as rn
  96. FROM chat_completions
  97. )
  98. WHERE rn = 1;
  99. """
  100. with pd.ExcelWriter(excel_path, engine="openpyxl") as writer:
  101. for trial_index, each_trial in enumerate(dbnames):
  102. result_df = pd.DataFrame(
  103. columns=[
  104. "id",
  105. "status",
  106. "expected_answer",
  107. "final_answer",
  108. "cost",
  109. "latency",
  110. "num_of_llm_requests",
  111. "num_of_chat_messages",
  112. "prompt_tokens",
  113. "completion_tokens",
  114. "total_tokens",
  115. "model",
  116. ]
  117. )
  118. result_df_type_mapping = {
  119. "id": str,
  120. "status": bool,
  121. "expected_answer": str,
  122. "final_answer": str,
  123. "cost": float,
  124. "latency": float,
  125. "num_of_llm_requests": int,
  126. "num_of_chat_messages": int,
  127. "prompt_tokens": int,
  128. "completion_tokens": int,
  129. "total_tokens": int,
  130. }
  131. for dbname, scorer_results in zip(each_trial, all_results):
  132. task_id = scorer_results[0]
  133. scorer_result = scorer_results[trial_index + 1]
  134. status, expected_answer, final_answer = (
  135. scorer_result if scorer_result else (False, "", "")
  136. )
  137. con = sqlite3.connect(dbname)
  138. # TODO: if large amount of data, add chunksize
  139. telemetry_df = pd.read_sql_query(query, con)
  140. earliest_starttime = pd.to_datetime(
  141. telemetry_df["start_time"], format="%Y-%m-%d %H:%M:%S.%f"
  142. ).min()
  143. latest_endtime = pd.to_datetime(
  144. telemetry_df["end_time"], format="%Y-%m-%d %H:%M:%S.%f"
  145. ).max()
  146. num_of_chat_messages = get_number_of_chat_messages(
  147. chat_messages_dir=os.path.dirname(dbname)
  148. )
  149. result = {
  150. "id": task_id,
  151. "status": status,
  152. "expected_answer": expected_answer,
  153. "final_answer": final_answer,
  154. "cost": telemetry_df["cost"].sum(),
  155. "latency": (
  156. latest_endtime - earliest_starttime
  157. ).total_seconds(),
  158. "num_of_llm_requests": len(telemetry_df),
  159. "num_of_chat_messages": num_of_chat_messages,
  160. "prompt_tokens": telemetry_df["response"]
  161. .apply(
  162. lambda x: json.loads(x)["usage"]["prompt_tokens"]
  163. if "usage" in json.loads(x)
  164. and "prompt_tokens" in json.loads(x)["usage"]
  165. else 0
  166. )
  167. .sum(),
  168. "completion_tokens": telemetry_df["response"]
  169. .apply(
  170. lambda x: json.loads(x)["usage"]["completion_tokens"]
  171. if "usage" in json.loads(x)
  172. and "completion_tokens" in json.loads(x)["usage"]
  173. else 0
  174. )
  175. .sum(),
  176. "total_tokens": telemetry_df["response"]
  177. .apply(
  178. lambda x: json.loads(x)["usage"]["total_tokens"]
  179. if "usage" in json.loads(x)
  180. and "total_tokens" in json.loads(x)["usage"]
  181. else 0
  182. )
  183. .sum(),
  184. "model": telemetry_df["response"]
  185. .apply(
  186. lambda x: json.loads(x)["model"]
  187. if "model" in json.loads(x)
  188. else ""
  189. )
  190. .unique(),
  191. }
  192. result_df = result_df.astype(result_df_type_mapping)
  193. result_df = pd.concat(
  194. [result_df, pd.DataFrame([result])], ignore_index=True
  195. )
  196. result_df.to_excel(
  197. writer, sheet_name=f"trial_{trial_index}", index=False
  198. )
  199. if __name__ == "__main__" and __package__ is None:
  200. main(sys.argv)