geminiDeveloper's picture
Upload 19 files
f03667b verified
Raw
History Blame Contribute Delete
15.1 kB
from __future__ import annotations
import argparse
import json
import shutil
import subprocess
import sys
import time
from collections.abc import Iterable
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from .backend import generate_reply, generate_replies
from .prompts import build_system_prompt
from .protocol import extract_tool_actions
from .tools import execute_actions, workspace_subprocess_env
from .types import TaskRunState, TaskSpec
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def run_task(
*,
spec: TaskSpec,
result_root: Path,
llm: Any,
tokenizer: Any,
sampling_params: Any,
args: argparse.Namespace,
) -> dict[str, Any]:
prepared = prepare_task_run_state(spec=spec, result_root=result_root, args=args)
if isinstance(prepared, dict):
return prepared
state = prepared
try:
while state.status == "running" and state.steps_used < args.max_steps:
reply = generate_reply(
llm=llm,
tokenizer=tokenizer,
sampling_params=sampling_params,
messages=state.messages,
enable_thinking=args.enable_thinking,
)
process_task_reply(state, reply, args=args)
except Exception as exc:
state.status = "failed"
state.error = f"{type(exc).__name__}: {exc}"
state.events.append({"step": state.steps_used + 1, "error": state.error})
write_task_state_history(state)
raise
return finalize_task_state(state, args=args)
def prepare_task_run_state(
*,
spec: TaskSpec,
result_root: Path,
args: argparse.Namespace,
) -> TaskRunState | dict[str, Any]:
result_dir = result_root / spec.task_id
if result_dir.exists():
if args.overwrite:
shutil.rmtree(result_dir)
elif args.resume and is_completed_result(result_dir):
print(f"[skip] {spec.task_id}: completed result exists at {result_dir}", file=sys.stderr)
return {"task_id": spec.task_id, "status": "skipped", "result_dir": str(result_dir)}
else:
raise FileExistsError(f"result dir already exists: {result_dir}; pass --overwrite or --resume")
result_dir.mkdir(parents=True, exist_ok=False)
workspace_after = result_dir / "workspace_after"
workspace_before = result_dir / "workspace_before"
workspace_after.mkdir(parents=True, exist_ok=False)
prompt_text = spec.prompt_path.read_text(encoding="utf-8")
shutil.copy2(spec.prompt_path, result_dir / "task_prompt.md")
if spec.verifier_path is not None:
shutil.copy2(spec.verifier_path, result_dir / "verify_workplace.py")
env_result = run_env_builder(spec.env_builder_path, workspace_after)
shutil.copytree(workspace_after, workspace_before)
messages = build_initial_messages(
prompt_text=prompt_text,
workspace_after=workspace_after,
args=args,
)
state = TaskRunState(
spec=spec,
result_dir=result_dir,
workspace_before=workspace_before,
workspace_after=workspace_after,
history_path=result_dir / "conversation_history.json",
metadata_path=result_dir / "runner_metadata.json",
prompt_text=prompt_text,
env_result=env_result,
started_at=utc_now(),
messages=messages,
)
write_task_state_history(state)
return state
def build_initial_messages(
*,
prompt_text: str,
workspace_after: Path,
args: argparse.Namespace,
) -> list[dict[str, str]]:
return [
{
"role": "system",
"content": build_system_prompt(
args.allow_python_tool,
workspace_dir=workspace_after,
model=args.model,
max_steps=args.max_steps,
),
},
{
"role": "user",
"content": (
"Solve this task by using Nanoclaw-compatible tool calls to inspect and modify the workspace.\n"
"Only provide a final answer after the requested workspace changes are complete.\n\n"
f"Task:\n{prompt_text}"
),
},
]
def run_tasks_batched(
*,
specs: list[TaskSpec],
result_root: Path,
llm: Any,
tokenizer: Any,
sampling_params: Any,
args: argparse.Namespace,
) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
states: list[TaskRunState] = []
for spec in specs:
print(f"[prepare] {spec.task_id}", file=sys.stderr)
try:
prepared = prepare_task_run_state(spec=spec, result_root=result_root, args=args)
except Exception as exc:
result = {
"task_id": spec.task_id,
"status": "failed",
"result_dir": str(result_root / spec.task_id),
"error": f"{type(exc).__name__}: {exc}",
}
results.append(result)
print(f"[error] {spec.task_id}: {result['error']}", file=sys.stderr)
continue
if isinstance(prepared, dict):
results.append(prepared)
else:
states.append(prepared)
while True:
active_states = [state for state in states if state.status == "running"]
if not active_states:
break
current_batch = active_states[: args.agent_batch_size]
print(
"[batch] "
+ ", ".join(f"{state.spec.task_id}:step{state.steps_used + 1}" for state in current_batch),
file=sys.stderr,
)
try:
replies = generate_replies(
llm=llm,
tokenizer=tokenizer,
sampling_params=sampling_params,
message_batches=[state.messages for state in current_batch],
enable_thinking=args.enable_thinking,
)
for state, reply in zip(current_batch, replies, strict=True):
process_task_reply(state, reply, args=args)
except Exception as exc:
error = f"{type(exc).__name__}: {exc}"
for state in current_batch:
state.status = "failed"
state.error = error
state.events.append({"step": state.steps_used + 1, "error": error})
write_task_state_history(state)
for state in states:
results.append(finalize_task_state(state, args=args))
return results
def process_task_reply(state: TaskRunState, reply: str, *, args: argparse.Namespace) -> None:
state.steps_used += 1
step = state.steps_used
state.messages.append({"role": "assistant", "content": reply})
try:
actions = extract_tool_actions(reply)
except ValueError as exc:
if is_final_text_response(reply):
state.status = "completed"
state.final_answer = reply.strip()
state.events.append(
{
"step": step,
"reply": reply,
"is_final": True,
"final_response_mode": "plain_text_without_tool_calls",
}
)
write_task_state_history(state)
return
observation = f"Action parse error: {exc}. Output JSON tool_calls/actions or provide a plain final answer only when the task is complete."
state.events.append({"step": step, "reply": reply, "error": observation})
if step >= args.max_steps:
state.status = "failed"
state.error = f"exceeded max steps ({args.max_steps}) without valid tool call or final answer"
else:
state.messages.append({"role": "user", "content": f"Observation:\n{observation}"})
write_task_state_history(state)
return
action_events, observation, is_final, final_answer = execute_actions(
actions,
state.workspace_after,
args=args,
step=step,
)
state.events.append(
{
"step": step,
"reply": reply,
"actions": action_events,
"observation": observation,
"is_final": is_final,
}
)
if is_final:
state.status = "completed"
state.final_answer = final_answer or ""
write_task_state_history(state)
return
if step >= args.max_steps:
state.status = "failed"
state.error = f"exceeded max steps ({args.max_steps}) without final answer"
else:
state.messages.append({"role": "user", "content": f"Observation:\n{observation}"})
write_task_state_history(state)
def is_final_text_response(reply: str) -> bool:
stripped = reply.strip()
if not stripped:
return False
if stripped.startswith("```"):
return False
return stripped[0] not in "[{"
def finalize_task_state(state: TaskRunState, *, args: argparse.Namespace) -> dict[str, Any]:
if state.status == "running":
state.status = "failed"
state.error = state.error or f"exceeded max steps ({args.max_steps}) without final answer"
if args.run_verifier and state.spec.verifier_path is not None:
state.verifier_result = run_verifier(
state.result_dir / "verify_workplace.py",
state.workspace_after,
timeout=args.verifier_timeout,
)
write_task_state_history(state)
metadata = {
"task_id": state.spec.task_id,
"status": state.status,
"error": state.error,
"final_answer": state.final_answer,
"steps_used": state.steps_used,
"started_at": state.started_at,
"finished_at": utc_now(),
"result_dir": str(state.result_dir),
"prompt_path": str(state.spec.prompt_path),
"env_builder_path": str(state.spec.env_builder_path),
"verifier_source_path": str(state.spec.verifier_path) if state.spec.verifier_path else None,
"workspace_before": str(state.workspace_before),
"workspace_after": str(state.workspace_after),
"conversation_history": str(state.history_path),
"env_builder": state.env_result,
"verifier": state.verifier_result,
"model": args.model,
"tokenizer": args.tokenizer or args.model,
"max_steps": args.max_steps,
"agent_batch_size": args.agent_batch_size,
"allow_python_tool": args.allow_python_tool,
"tool_call_transport": "local_vllm_json_text",
}
state.metadata_path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return {
"task_id": state.spec.task_id,
"status": state.status,
"result_dir": str(state.result_dir),
"error": state.error,
}
def write_task_state_history(state: TaskRunState) -> None:
write_history(
state.history_path,
spec=state.spec,
status=state.status,
final_answer=state.final_answer,
error=state.error,
messages=state.messages,
events=state.events,
started_at=state.started_at,
steps_used=state.steps_used,
)
def is_completed_result(result_dir: Path) -> bool:
metadata_path = result_dir / "runner_metadata.json"
if not metadata_path.is_file():
return False
try:
payload = json.loads(metadata_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return False
return payload.get("status") == "completed"
def run_env_builder(env_builder_path: Path, workspace: Path) -> dict[str, Any]:
started = time.time()
process = subprocess.run(
[sys.executable, str(env_builder_path)],
cwd=workspace,
text=True,
capture_output=True,
env=workspace_subprocess_env(workspace),
check=False,
)
result = {
"returncode": process.returncode,
"stdout": process.stdout,
"stderr": process.stderr,
"elapsed_seconds": round(time.time() - started, 3),
}
if process.returncode != 0:
raise RuntimeError(
f"env_builder.py failed for {env_builder_path} with code {process.returncode}\n"
f"stdout:\n{process.stdout}\n\nstderr:\n{process.stderr}"
)
return result
def run_verifier(verifier_path: Path, workspace: Path, *, timeout: float) -> dict[str, Any]:
started = time.time()
try:
process = subprocess.run(
[sys.executable, str(verifier_path), str(workspace)],
cwd=verifier_path.parent,
text=True,
capture_output=True,
env=workspace_subprocess_env(workspace),
timeout=timeout,
check=False,
)
result: dict[str, Any] = {
"returncode": process.returncode,
"stdout": process.stdout,
"stderr": process.stderr,
"elapsed_seconds": round(time.time() - started, 3),
}
except subprocess.TimeoutExpired as exc:
result = {
"returncode": None,
"stdout": exc.stdout or "",
"stderr": exc.stderr or "",
"elapsed_seconds": round(time.time() - started, 3),
"error": f"verifier timed out after {timeout:g}s",
}
score_path = workspace / "workplace_score.json"
if score_path.is_file():
try:
result["workplace_score"] = json.loads(score_path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
result["workplace_score_error"] = str(exc)
return result
def write_history(
path: Path,
*,
spec: TaskSpec,
status: str,
final_answer: str | None,
error: str | None,
messages: list[dict[str, str]],
events: list[dict[str, Any]],
started_at: str,
steps_used: int,
) -> None:
payload = {
"task_id": spec.task_id,
"status": status,
"final_answer": final_answer,
"error": error,
"started_at": started_at,
"updated_at": utc_now(),
"steps_used": steps_used,
"messages": messages,
"events": events,
}
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def write_summary(output_root: Path, results: list[dict[str, Any]], started_at: str) -> None:
summary = {
"started_at": started_at,
"finished_at": utc_now(),
"total": len(results),
"completed": sum(1 for result in results if result.get("status") == "completed"),
"failed": sum(1 for result in results if result.get("status") == "failed"),
"skipped": sum(1 for result in results if result.get("status") == "skipped"),
"results": results,
}
output_root.mkdir(parents=True, exist_ok=True)
(output_root / "summary.json").write_text(
json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
def iter_jsonl_results(results: Iterable[dict[str, Any]]) -> str:
return "".join(json.dumps(result, ensure_ascii=False) + "\n" for result in results)