run_replay.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. """Replay a trajectory"""
  2. import json
  3. import os
  4. import yaml
  5. from argparse import ArgumentParser
  6. from sweagent.environment.utils import is_from_github_url
  7. from typing import Any, Dict, List
  8. import run as runscript
  9. def process_single_traj(traj_path: str, config_file: str, data_path: str, suffix: str, *, forward_args: List[str]):
  10. """
  11. Args:
  12. traj_path (str): _description_
  13. config_file (str): _description_
  14. data_path (str): _description_
  15. suffix (str): _description_
  16. forward_args (List[str]): Passed to run.py
  17. Raises:
  18. ValueError: Incorrect paths or other config issue
  19. Returns:
  20. None
  21. """
  22. replay_action_trajs_path = "temp_replay.jsonl"
  23. # Open trajectory file, extract responses as actions
  24. if traj_path.endswith(".yaml"):
  25. traj_data = dict()
  26. with open(traj_path, "r") as f:
  27. traj_data["history"] = yaml.safe_load(f)
  28. else:
  29. traj_data = json.load(open(traj_path, "r"))
  30. actions = [x["content"] for x in traj_data["history"] if x["role"] == "assistant"]
  31. instance_id = traj_path.split("/")[-1].split(".")[0]
  32. with open(replay_action_trajs_path, "w") as f:
  33. print(
  34. json.dumps({instance_id: actions}),
  35. file=f,
  36. end="\n",
  37. flush=True
  38. )
  39. # Get data_path from args.yaml
  40. if data_path is None:
  41. args_path = os.path.join(
  42. os.path.dirname(traj_path),
  43. "args.yaml"
  44. )
  45. args = yaml.safe_load(open(args_path))
  46. data_path = args['environment']['data_path']
  47. # Identify the relevant task instance and create it
  48. def create_task_instances_tmp_file(data: List[Dict[str, Any]]) -> str:
  49. """Helper function to create a temporary file to write task instances to.
  50. Returns path to the temporary file.
  51. """
  52. data = [d for d in data if d["instance_id"] == instance_id]
  53. tmp_path = instance_id + ".jsonl"
  54. with open(tmp_path, "w") as f:
  55. for d in data:
  56. print(json.dumps(d), file=f, end="\n", flush=True)
  57. return replay_task_instances_path
  58. is_github = False
  59. if data_path.endswith(".jsonl"):
  60. replay_task_instances_path = create_task_instances_tmp_file([json.loads(x) for x in open(data_path, "r").readlines()])
  61. elif data_path.endswith(".json"):
  62. replay_task_instances_path = create_task_instances_tmp_file(json.load(open(data_path)))
  63. elif is_from_github_url(data_path):
  64. is_github = True
  65. replay_task_instances_path = data_path
  66. else:
  67. raise ValueError("--data_path must be a .json or .jsonl")
  68. # Call run.py via subprocess
  69. run_args = [
  70. "--config_file", config_file,
  71. "--data_path", replay_task_instances_path,
  72. "--install_environment", "True",
  73. "--model_name", "replay",
  74. "--replay_path", replay_action_trajs_path,
  75. *forward_args,
  76. ]
  77. if is_github:
  78. # Not sure if this only applies to github urls for data_path
  79. run_args.extend(["--skip_existing", "False"])
  80. if suffix is not None:
  81. run_args.extend(["--suffix", suffix])
  82. script_args = runscript.get_args(run_args)
  83. runscript.main(script_args)
  84. os.remove(replay_action_trajs_path)
  85. try:
  86. os.remove(replay_task_instances_path)
  87. except FileNotFoundError:
  88. pass
  89. def main(
  90. traj_path: str,
  91. config_file: str,
  92. data_path: str,
  93. suffix: str,
  94. *,
  95. forward_args: List[str],
  96. ):
  97. process_single_traj(traj_path, config_file, data_path, suffix, forward_args=forward_args)
  98. def get_args(args=None):
  99. parser = ArgumentParser(description=__doc__)
  100. parser.add_argument("--traj_path", help="Path to trajectory to replay", default=None)
  101. parser.add_argument("--config_file", help="Path to template", required=True)
  102. parser.add_argument("--data_path", help="(Optional) Path to data file containing task instances ref'ed by replay trajectories", default=None)
  103. parser.add_argument("--suffix", help="(Optional) Suffix argument appended to end of traj path", default=None)
  104. args, remaining_args = parser.parse_known_args(args=args)
  105. return args, remaining_args
  106. if __name__ == "__main__":
  107. args, remaining_args = get_args()
  108. main(**vars(args), forward_args=remaining_args)