shared.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import json
  2. import logging
  3. import multiprocessing as mp
  4. import os
  5. import pathlib
  6. import subprocess
  7. import time
  8. import traceback
  9. from concurrent.futures import ProcessPoolExecutor, as_completed
  10. from typing import Any, Awaitable, Callable, TextIO
  11. import pandas as pd
  12. from pydantic import BaseModel
  13. from tqdm import tqdm
  14. from openhands.controller.state.state import State
  15. from openhands.core.config import LLMConfig
  16. from openhands.core.logger import get_console_handler
  17. from openhands.core.logger import openhands_logger as logger
  18. from openhands.events.action import Action
  19. from openhands.events.action.message import MessageAction
  20. class EvalMetadata(BaseModel):
  21. agent_class: str
  22. llm_config: LLMConfig
  23. max_iterations: int
  24. eval_output_dir: str
  25. start_time: str
  26. git_commit: str
  27. dataset: str | None = None
  28. data_split: str | None = None
  29. details: dict[str, Any] | None = None
  30. def model_dump(self, *args, **kwargs):
  31. dumped_dict = super().model_dump(*args, **kwargs)
  32. # avoid leaking sensitive information
  33. dumped_dict['llm_config'] = self.llm_config.to_safe_dict()
  34. return dumped_dict
  35. def model_dump_json(self, *args, **kwargs):
  36. dumped = super().model_dump_json(*args, **kwargs)
  37. dumped_dict = json.loads(dumped)
  38. logger.debug(f'Dumped metadata: {dumped_dict}')
  39. # avoid leaking sensitive information
  40. dumped_dict['llm_config'] = self.llm_config.to_safe_dict()
  41. return json.dumps(dumped_dict)
  42. class EvalOutput(BaseModel):
  43. # NOTE: User-specified
  44. instance_id: str
  45. # output of the evaluation
  46. # store anything that is needed for the score calculation
  47. test_result: dict[str, Any]
  48. instruction: str | None = None
  49. # Interaction info
  50. metadata: EvalMetadata | None = None
  51. history: list[tuple[dict[str, Any], dict[str, Any]]] | None = None
  52. metrics: dict[str, Any] | None = None
  53. error: str | None = None
  54. # Optionally save the input test instance
  55. instance: dict[str, Any] | None = None
  56. def model_dump(self, *args, **kwargs):
  57. dumped_dict = super().model_dump(*args, **kwargs)
  58. # Remove None values
  59. dumped_dict = {k: v for k, v in dumped_dict.items() if v is not None}
  60. # Apply custom serialization for metadata (to avoid leaking sensitive information)
  61. if self.metadata is not None:
  62. dumped_dict['metadata'] = self.metadata.model_dump()
  63. return dumped_dict
  64. def model_dump_json(self, *args, **kwargs):
  65. dumped = super().model_dump_json(*args, **kwargs)
  66. dumped_dict = json.loads(dumped)
  67. # Apply custom serialization for metadata (to avoid leaking sensitive information)
  68. if 'metadata' in dumped_dict:
  69. dumped_dict['metadata'] = json.loads(self.metadata.model_dump_json())
  70. return json.dumps(dumped_dict)
  71. def codeact_user_response(
  72. state: State,
  73. encapsulate_solution: bool = False,
  74. try_parse: Callable[[Action], str] | None = None,
  75. ) -> str:
  76. encaps_str = (
  77. (
  78. 'Please encapsulate your final answer (answer ONLY) within <solution> and </solution>.\n'
  79. 'For example: The answer to the question is <solution> 42 </solution>.\n'
  80. )
  81. if encapsulate_solution
  82. else ''
  83. )
  84. msg = (
  85. 'Please continue working on the task on whatever approach you think is suitable.\n'
  86. 'If you think you have solved the task, please first send your answer to user through message and then <execute_bash> exit </execute_bash>.\n'
  87. f'{encaps_str}'
  88. 'IMPORTANT: YOU SHOULD NEVER ASK FOR HUMAN HELP.\n'
  89. )
  90. if state.history:
  91. # check if the last action has an answer, if so, early exit
  92. if try_parse is not None:
  93. last_action = state.history.get_last_action()
  94. ans = try_parse(last_action)
  95. if ans is not None:
  96. return '/exit'
  97. # check if the agent has tried to talk to the user 3 times, if so, let the agent know it can give up
  98. user_msgs = [
  99. event
  100. for event in state.history.get_events()
  101. if isinstance(event, MessageAction) and event.source == 'user'
  102. ]
  103. if len(user_msgs) >= 2:
  104. # let the agent know that it can give up when it has tried 3 times
  105. return (
  106. msg
  107. + 'If you want to give up, run: <execute_bash> exit </execute_bash>.\n'
  108. )
  109. return msg
  110. def cleanup():
  111. print('Cleaning up child processes...')
  112. for process in mp.active_children():
  113. print(f'Terminating child process: {process.name}')
  114. process.terminate()
  115. process.join()
  116. def make_metadata(
  117. llm_config: LLMConfig,
  118. dataset_name: str,
  119. agent_class: str,
  120. max_iterations: int,
  121. eval_note: str | None,
  122. eval_output_dir: str,
  123. data_split: str | None = None,
  124. details: dict[str, Any] | None = None,
  125. ) -> EvalMetadata:
  126. model_name = llm_config.model.split('/')[-1]
  127. model_path = model_name.replace(':', '_')
  128. eval_note = f'_N_{eval_note}' if eval_note else ''
  129. eval_output_path = os.path.join(
  130. eval_output_dir,
  131. dataset_name,
  132. agent_class,
  133. f'{model_path}_maxiter_{max_iterations}{eval_note}',
  134. )
  135. pathlib.Path(eval_output_path).mkdir(parents=True, exist_ok=True)
  136. pathlib.Path(os.path.join(eval_output_path, 'logs')).mkdir(
  137. parents=True, exist_ok=True
  138. )
  139. logger.info(f'Using evaluation output directory: {eval_output_path}')
  140. metadata = EvalMetadata(
  141. agent_class=agent_class,
  142. llm_config=llm_config,
  143. max_iterations=max_iterations,
  144. eval_output_dir=eval_output_path,
  145. start_time=time.strftime('%Y-%m-%d %H:%M:%S'),
  146. git_commit=subprocess.check_output(['git', 'rev-parse', 'HEAD'])
  147. .decode('utf-8')
  148. .strip(),
  149. dataset=dataset_name,
  150. data_split=data_split,
  151. details=details,
  152. )
  153. metadata_json = metadata.model_dump_json()
  154. logger.info(f'Metadata: {metadata_json}')
  155. with open(os.path.join(eval_output_path, 'metadata.json'), 'w') as f:
  156. f.write(metadata_json)
  157. return metadata
  158. def prepare_dataset(
  159. dataset: pd.DataFrame,
  160. output_file: str,
  161. eval_n_limit: int,
  162. eval_ids: list[str] | None = None,
  163. skip_num: int | None = None,
  164. ):
  165. assert (
  166. 'instance_id' in dataset.columns
  167. ), "Expected 'instance_id' column in the dataset. You should define your own unique identifier for each instance and use it as the 'instance_id' column."
  168. id_column = 'instance_id'
  169. logger.info(f'Writing evaluation output to {output_file}')
  170. finished_ids: set[str] = set()
  171. if os.path.exists(output_file):
  172. with open(output_file, 'r') as f:
  173. for line in f:
  174. data = json.loads(line)
  175. finished_ids.add(str(data[id_column]))
  176. logger.warning(
  177. f'\nOutput file {output_file} already exists. Loaded {len(finished_ids)} finished instances.'
  178. )
  179. if eval_ids:
  180. eval_ids_converted = [dataset[id_column].dtype.type(id) for id in eval_ids]
  181. dataset = dataset[dataset[id_column].isin(eval_ids_converted)]
  182. logger.info(f'Limiting evaluation to {len(eval_ids)} specific instances.')
  183. elif skip_num and skip_num >= 0:
  184. skip_num = min(skip_num, len(dataset))
  185. dataset = dataset.iloc[skip_num:]
  186. logger.info(
  187. f'Starting evaluation with skipping first {skip_num} instances ({len(dataset)} instances to run).'
  188. )
  189. if eval_n_limit and eval_n_limit > 0:
  190. dataset = dataset.head(eval_n_limit)
  191. logger.info(f'Limiting evaluation to {eval_n_limit} instances.')
  192. elif eval_n_limit and eval_n_limit > 0:
  193. dataset = dataset.head(eval_n_limit)
  194. logger.info(f'Limiting evaluation to first {eval_n_limit} instances.')
  195. new_dataset = [
  196. instance
  197. for _, instance in dataset.iterrows()
  198. if str(instance[id_column]) not in finished_ids
  199. ]
  200. logger.info(
  201. f'Finished instances: {len(finished_ids)}, Remaining instances: {len(new_dataset)}'
  202. )
  203. return pd.DataFrame(new_dataset)
  204. def update_progress(
  205. result: EvalOutput,
  206. pbar: tqdm,
  207. output_fp: TextIO,
  208. ):
  209. """Update the progress bar and write the result to the output file."""
  210. pbar.update(1)
  211. pbar.set_description(f'Instance {result.instance_id}')
  212. pbar.set_postfix_str(f'Test Result: {result.test_result}')
  213. logger.info(
  214. f'Finished evaluation for instance {result.instance_id}: {str(result.test_result)[:300]}...\n'
  215. )
  216. output_fp.write(json.dumps(result.model_dump()) + '\n')
  217. output_fp.flush()
  218. def _process_instance_wrapper(
  219. process_instance_func: Callable[[pd.Series, EvalMetadata, bool], EvalOutput],
  220. instance: pd.Series,
  221. metadata: EvalMetadata,
  222. use_mp: bool,
  223. max_retries: int = 5,
  224. ) -> EvalOutput:
  225. """Wrap the process_instance_func to handle retries and errors.
  226. Retry an instance up to max_retries times if it fails (e.g., due to transient network/runtime issues).
  227. """
  228. for attempt in range(max_retries + 1):
  229. try:
  230. result = process_instance_func(instance, metadata, use_mp)
  231. return result
  232. except Exception as e:
  233. error = str(e)
  234. stacktrace = traceback.format_exc()
  235. if attempt == max_retries:
  236. logger.exception(e)
  237. msg = (
  238. '-' * 10
  239. + '\n'
  240. + f'Error in instance [{instance.instance_id}]: {error}. Stacktrace:\n{stacktrace}'
  241. + '\n'
  242. + f'[Encountered after {max_retries} retries. Please check the logs and report the issue.]'
  243. + '-' * 10
  244. )
  245. # Raise an error after all retries & stop the evaluation
  246. raise RuntimeError(
  247. f'Maximum error retries reached for instance {instance.instance_id}'
  248. ) from e
  249. msg = (
  250. '-' * 10
  251. + '\n'
  252. + f'Error in instance [{instance.instance_id}]: {error}. Stacktrace:\n{stacktrace}'
  253. + '\n'
  254. + '-' * 10
  255. + f'[The above error occurred. Retrying... (attempt {attempt + 1} of {max_retries})]'
  256. + '-' * 10
  257. + '\n'
  258. )
  259. logger.error(msg)
  260. if use_mp:
  261. print(msg) # use print to directly print to console
  262. time.sleep(5)
  263. def run_evaluation(
  264. dataset: pd.DataFrame,
  265. metadata: EvalMetadata | None,
  266. output_file: str,
  267. num_workers: int,
  268. process_instance_func: Callable[
  269. [pd.Series, EvalMetadata, bool], Awaitable[EvalOutput]
  270. ],
  271. max_retries: int = 5, # number of retries for each instance
  272. ):
  273. use_multiprocessing = num_workers > 1
  274. if metadata is not None:
  275. logger.info(
  276. f'Evaluation started with Agent {metadata.agent_class}:\n'
  277. f'model {metadata.llm_config.model}, max iterations {metadata.max_iterations}.\n'
  278. )
  279. else:
  280. logger.info(f'Evaluation started with {num_workers} workers.')
  281. total_instances = len(dataset)
  282. pbar = tqdm(total=total_instances, desc='Instances processed')
  283. output_fp = open(output_file, 'a')
  284. try:
  285. if use_multiprocessing:
  286. with ProcessPoolExecutor(num_workers) as executor:
  287. futures = [
  288. executor.submit(
  289. _process_instance_wrapper,
  290. process_instance_func=process_instance_func,
  291. instance=instance,
  292. metadata=metadata,
  293. use_mp=True,
  294. max_retries=max_retries,
  295. )
  296. for _, instance in dataset.iterrows()
  297. ]
  298. for future in as_completed(futures):
  299. result = future.result()
  300. update_progress(result, pbar, output_fp)
  301. else:
  302. for _, instance in dataset.iterrows():
  303. result = _process_instance_wrapper(
  304. process_instance_func=process_instance_func,
  305. instance=instance,
  306. metadata=metadata,
  307. use_mp=False,
  308. max_retries=max_retries,
  309. )
  310. update_progress(result, pbar, output_fp)
  311. except KeyboardInterrupt:
  312. print('\nKeyboardInterrupt received. Cleaning up...\n')
  313. cleanup()
  314. output_fp.close()
  315. logger.info('\nEvaluation finished.\n')
  316. def reset_logger_for_multiprocessing(
  317. logger: logging.Logger, instance_id: str, log_dir: str
  318. ):
  319. """Reset the logger for multiprocessing.
  320. Save logs to a separate file for each process, instead of trying to write to the
  321. same file/console from multiple processes.
  322. """
  323. # Set up logger
  324. log_file = os.path.join(
  325. log_dir,
  326. f'instance_{instance_id}.log',
  327. )
  328. # Remove all existing handlers from logger
  329. for handler in logger.handlers[:]:
  330. logger.removeHandler(handler)
  331. # add back the console handler to print ONE line
  332. logger.addHandler(get_console_handler())
  333. logger.info(
  334. f'Starting evaluation for instance {instance_id}.\n'
  335. f'Hint: run "tail -f {log_file}" to see live logs in a separate shell'
  336. )
  337. # Remove all existing handlers from logger
  338. for handler in logger.handlers[:]:
  339. logger.removeHandler(handler)
  340. os.makedirs(os.path.dirname(log_file), exist_ok=True)
  341. file_handler = logging.FileHandler(log_file)
  342. file_handler.setFormatter(
  343. logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
  344. )
  345. logger.addHandler(file_handler)