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 7.7 kB

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