File size: 12,097 Bytes
8b41737 7023780 8b41737 7023780 8b41737 7023780 8b41737 7023780 8b41737 7023780 499ba81 7023780 499ba81 7023780 499ba81 7023780 8b41737 7023780 8b41737 7023780 8b41737 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | import json
import hashlib
from flask import Blueprint, request, jsonify
from datasets import load_dataset
bp = Blueprint("harbor_datasets", __name__, url_prefix="/api/harbor/datasets")
_cache: dict[str, dict] = {}
def _make_id(repo: str, split: str) -> str:
key = f"{repo}:{split}"
return hashlib.md5(key.encode()).hexdigest()[:12]
def _parse_trajectory(traj_json: str) -> dict:
"""Parse ATIF trajectory JSON into structured steps (v1.2 and v1.5)."""
if not traj_json:
return {"steps": [], "agent_info": {}, "final_metrics": {}}
try:
traj = json.loads(traj_json) if isinstance(traj_json, str) else traj_json
except (json.JSONDecodeError, TypeError):
return {"steps": [], "agent_info": {}, "final_metrics": {}}
steps = []
for step in traj.get("steps", []):
parsed = {
"index": len(steps),
"source": step.get("source", "unknown"),
"message": step.get("message", ""),
"timestamp": step.get("timestamp"),
}
if step.get("source") == "agent":
parsed["reasoning"] = step.get("reasoning_content", "")
parsed["tool_calls"] = []
for tc in step.get("tool_calls", []):
args = tc.get("arguments", {})
tool_call = {
"function": tc.get("function_name", ""),
"arguments": args,
}
# v1.2 uses "command", v1.5 uses "cmd"
cmd = args.get("command", "") or args.get("cmd", "")
if cmd:
tool_call["command"] = cmd
parsed["tool_calls"].append(tool_call)
obs = step.get("observation", {})
if obs:
if isinstance(obs, dict) and "results" in obs:
results = obs["results"]
if results:
parsed["observation"] = results[0].get("content", "") if isinstance(results[0], dict) else str(results[0])
else:
parsed["observation"] = ""
elif isinstance(obs, str):
parsed["observation"] = obs
else:
parsed["observation"] = json.dumps(obs)
parsed["metrics"] = step.get("metrics", {})
elif step.get("source") == "system":
pass # message is enough
elif step.get("source") == "user":
pass # message is enough
steps.append(parsed)
return {
"steps": steps,
"agent_info": traj.get("agent", {}),
"final_metrics": traj.get("final_metrics", {}),
}
def _parse_trajectory_raw(traj_raw: str) -> list[dict]:
"""Parse trajectory_raw into chat-style steps.
Handles two formats:
1. Flat list of OpenAI messages
2. Dict with {info, messages, trajectory_format} (mini-swe-agent format)
"""
if not traj_raw:
return []
try:
parsed = json.loads(traj_raw) if isinstance(traj_raw, str) else traj_raw
except (json.JSONDecodeError, TypeError):
return []
# Extract messages list and optional info
info = {}
if isinstance(parsed, dict):
info = parsed.get("info", {})
messages = parsed.get("messages", [])
elif isinstance(parsed, list):
messages = parsed
else:
return []
steps = []
for i, msg in enumerate(messages):
if not isinstance(msg, dict):
continue
role = msg.get("role", "unknown")
content = msg.get("content", "")
step = {
"index": i,
"role": role,
"content": content if isinstance(content, str) else json.dumps(content) if content else "",
}
# Assistant messages may have tool_calls (OpenAI format)
if role == "assistant" and "tool_calls" in msg:
tool_calls = msg["tool_calls"]
step["tool_calls"] = []
for tc in (tool_calls if isinstance(tool_calls, list) else []):
fn = tc.get("function", {})
call = {
"id": tc.get("id", ""),
"function": fn.get("name", ""),
"arguments_raw": fn.get("arguments", ""),
}
try:
args = json.loads(fn.get("arguments", "{}"))
call["arguments"] = args
if "command" in args:
call["command"] = args["command"]
except (json.JSONDecodeError, TypeError):
call["arguments"] = {}
step["tool_calls"].append(call)
# Tool messages have tool_call_id
if role == "tool":
step["tool_call_id"] = msg.get("tool_call_id", "")
steps.append(step)
# Attach info as metadata on first step if available
if steps and info:
steps[0]["_info"] = info
return steps
def _parse_agent_output_jsonl(agent_output: str) -> list[dict]:
"""Parse Codex-style JSONL agent_output into chat-style steps.
Codex emits newline-delimited JSON with item.completed events containing
reasoning, agent_message, and command_execution items. Falls back
gracefully if the format is unrecognised.
"""
if not agent_output:
return []
steps: list[dict] = []
idx = 0
for line in agent_output.strip().split("\n"):
try:
event = json.loads(line)
except (json.JSONDecodeError, TypeError):
continue
if event.get("type") != "item.completed":
continue
item = event.get("item", {})
item_type = item.get("type", "")
if item_type == "reasoning":
steps.append({
"index": idx,
"role": "assistant",
"content": item.get("text", ""),
"_reasoning": True,
})
idx += 1
elif item_type == "agent_message":
steps.append({
"index": idx,
"role": "assistant",
"content": item.get("text", ""),
})
idx += 1
elif item_type == "command_execution":
cmd = item.get("command", "")
call_id = item.get("call_id", item.get("id", ""))
# Assistant step with tool call
steps.append({
"index": idx,
"role": "assistant",
"content": "",
"tool_calls": [{
"id": call_id,
"function": "exec_command",
"arguments_raw": json.dumps({"command": cmd}),
"arguments": {"command": cmd},
"command": cmd,
}],
})
idx += 1
# Tool response step — Codex uses "aggregated_output", others use "output"
output = item.get("output", "") or item.get("aggregated_output", "")
exit_code = item.get("exit_code")
status = item.get("status", "")
response_text = output
if exit_code is not None:
header = f"[exit code: {exit_code}]"
if status:
header = f"[{status} — exit code: {exit_code}]"
response_text = f"{header}\n{output}" if output else header
steps.append({
"index": idx,
"role": "tool",
"content": response_text,
"tool_call_id": call_id,
})
idx += 1
return steps
def _build_instance_summary(row: dict) -> dict:
"""Build a summary for one instance row."""
return {
"instance_id": row.get("instance_id", ""),
"resolved": row.get("resolved", False),
"reward": row.get("reward", 0),
"model": row.get("model", ""),
"agent": row.get("agent", ""),
"duration_seconds": row.get("duration_seconds", 0),
"error": row.get("error", ""),
}
@bp.route("/load", methods=["POST"])
def load_dataset_endpoint():
data = request.get_json()
repo = data.get("repo", "").strip()
if not repo:
return jsonify({"error": "repo is required"}), 400
split = data.get("split", "train")
try:
ds = load_dataset(repo, split=split)
except Exception as e:
return jsonify({"error": f"Failed to load dataset: {e}"}), 400
ds_id = _make_id(repo, split)
# Build instance summaries and index
instances = []
instance_index = {}
for i in range(len(ds)):
row = ds[i]
summary = _build_instance_summary(row)
instances.append(summary)
instance_index[row.get("instance_id", "")] = i
_cache[ds_id] = {
"repo": repo,
"split": split,
"dataset": ds,
"instances": instances,
"instance_index": instance_index,
}
short_name = repo.rsplit("/", 1)[-1] if "/" in repo else repo
return jsonify({
"id": ds_id,
"repo": repo,
"name": short_name,
"split": split,
"instances": instances,
"n_instances": len(instances),
})
@bp.route("/", methods=["GET"])
def list_datasets():
result = []
for ds_id, info in _cache.items():
result.append({
"id": ds_id,
"repo": info["repo"],
"name": info["repo"].rsplit("/", 1)[-1] if "/" in info["repo"] else info["repo"],
"split": info["split"],
"n_instances": len(info["instances"]),
"instances": info["instances"],
})
return jsonify(result)
@bp.route("/<ds_id>/instances", methods=["GET"])
def get_instances(ds_id):
if ds_id not in _cache:
return jsonify({"error": "Dataset not loaded"}), 404
return jsonify(_cache[ds_id]["instances"])
@bp.route("/<ds_id>/instance/<path:instance_id>", methods=["GET"])
def get_instance(ds_id, instance_id):
"""Get full parsed trajectory for one instance."""
if ds_id not in _cache:
return jsonify({"error": "Dataset not loaded"}), 404
info = _cache[ds_id]
if instance_id not in info["instance_index"]:
return jsonify({"error": f"Instance {instance_id} not found"}), 404
idx = info["instance_index"][instance_id]
row = info["dataset"][idx]
# Parse ATIF trajectory
atif = _parse_trajectory(row.get("trajectory", ""))
# Parse raw trajectory (OpenAI messages), fall back to agent_output JSONL
raw_steps = _parse_trajectory_raw(row.get("trajectory_raw", ""))
if not raw_steps and row.get("agent_output"):
raw_steps = _parse_agent_output_jsonl(row["agent_output"])
return jsonify({
"instance_id": instance_id,
"resolved": row.get("resolved", False),
"reward": row.get("reward", 0),
"model": row.get("model", ""),
"agent": row.get("agent", ""),
"duration_seconds": row.get("duration_seconds", 0),
"error": row.get("error", ""),
"atif": atif,
"raw_steps": raw_steps,
"n_atif_steps": len(atif["steps"]),
"n_raw_steps": len(raw_steps),
})
@bp.route("/<ds_id>/instance/<path:instance_id>/raw", methods=["GET"])
def get_instance_raw(ds_id, instance_id):
"""Get raw logs: agent_stdout, setup_stderr, verifier_report."""
if ds_id not in _cache:
return jsonify({"error": "Dataset not loaded"}), 404
info = _cache[ds_id]
if instance_id not in info["instance_index"]:
return jsonify({"error": f"Instance {instance_id} not found"}), 404
idx = info["instance_index"][instance_id]
row = info["dataset"][idx]
return jsonify({
"instance_id": instance_id,
"agent_stdout": row.get("agent_stdout", ""),
"setup_stderr": row.get("setup_stderr", ""),
"verifier_report": row.get("verifier_report", ""),
"verifier_stdout": row.get("verifier_stdout", ""),
})
@bp.route("/<ds_id>", methods=["DELETE"])
def unload_dataset(ds_id):
if ds_id in _cache:
del _cache[ds_id]
return jsonify({"status": "ok"})
|