Upload 19 files
Browse files- vllm_nanoclaw_runtime/__init__.py +5 -0
- vllm_nanoclaw_runtime/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm_nanoclaw_runtime/__pycache__/backend.cpython-310.pyc +0 -0
- vllm_nanoclaw_runtime/__pycache__/cli.cpython-310.pyc +0 -0
- vllm_nanoclaw_runtime/__pycache__/prompts.cpython-310.pyc +0 -0
- vllm_nanoclaw_runtime/__pycache__/protocol.cpython-310.pyc +0 -0
- vllm_nanoclaw_runtime/__pycache__/runner.cpython-310.pyc +0 -0
- vllm_nanoclaw_runtime/__pycache__/tasks.cpython-310.pyc +0 -0
- vllm_nanoclaw_runtime/__pycache__/tools.cpython-310.pyc +0 -0
- vllm_nanoclaw_runtime/__pycache__/types.cpython-310.pyc +0 -0
- vllm_nanoclaw_runtime/backend.py +99 -0
- vllm_nanoclaw_runtime/cli.py +140 -0
- vllm_nanoclaw_runtime/prompts.py +168 -0
- vllm_nanoclaw_runtime/protocol.py +112 -0
- vllm_nanoclaw_runtime/run_qwen3_5_27b_nanoclaw_runtime_eager.sh +354 -0
- vllm_nanoclaw_runtime/runner.py +448 -0
- vllm_nanoclaw_runtime/tasks.py +78 -0
- vllm_nanoclaw_runtime/tools.py +466 -0
- vllm_nanoclaw_runtime/types.py +41 -0
vllm_nanoclaw_runtime/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local vLLM-backed Nanoclaw-compatible runtime."""
|
| 2 |
+
|
| 3 |
+
__all__ = ["__version__"]
|
| 4 |
+
|
| 5 |
+
__version__ = "0.2.0"
|
vllm_nanoclaw_runtime/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (232 Bytes). View file
|
|
|
vllm_nanoclaw_runtime/__pycache__/backend.cpython-310.pyc
ADDED
|
Binary file (2.78 kB). View file
|
|
|
vllm_nanoclaw_runtime/__pycache__/cli.cpython-310.pyc
ADDED
|
Binary file (5.46 kB). View file
|
|
|
vllm_nanoclaw_runtime/__pycache__/prompts.cpython-310.pyc
ADDED
|
Binary file (6.31 kB). View file
|
|
|
vllm_nanoclaw_runtime/__pycache__/protocol.cpython-310.pyc
ADDED
|
Binary file (3.16 kB). View file
|
|
|
vllm_nanoclaw_runtime/__pycache__/runner.cpython-310.pyc
ADDED
|
Binary file (11.5 kB). View file
|
|
|
vllm_nanoclaw_runtime/__pycache__/tasks.cpython-310.pyc
ADDED
|
Binary file (2.53 kB). View file
|
|
|
vllm_nanoclaw_runtime/__pycache__/tools.cpython-310.pyc
ADDED
|
Binary file (13.1 kB). View file
|
|
|
vllm_nanoclaw_runtime/__pycache__/types.cpython-310.pyc
ADDED
|
Binary file (1.65 kB). View file
|
|
|
vllm_nanoclaw_runtime/backend.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def build_llm(args: argparse.Namespace) -> Any:
|
| 8 |
+
from vllm import LLM
|
| 9 |
+
|
| 10 |
+
llm_kwargs: dict[str, Any] = {
|
| 11 |
+
"model": args.model,
|
| 12 |
+
"tokenizer": args.tokenizer or args.model,
|
| 13 |
+
"tensor_parallel_size": args.tensor_parallel_size,
|
| 14 |
+
"dtype": args.dtype,
|
| 15 |
+
"max_model_len": args.max_model_len,
|
| 16 |
+
"gpu_memory_utilization": args.gpu_memory_utilization,
|
| 17 |
+
"trust_remote_code": args.trust_remote_code,
|
| 18 |
+
"enforce_eager": args.enforce_eager,
|
| 19 |
+
"enable_prefix_caching": args.enable_prefix_caching,
|
| 20 |
+
}
|
| 21 |
+
if args.max_num_batched_tokens is not None:
|
| 22 |
+
llm_kwargs["max_num_batched_tokens"] = args.max_num_batched_tokens
|
| 23 |
+
if args.max_num_seqs is not None:
|
| 24 |
+
llm_kwargs["max_num_seqs"] = args.max_num_seqs
|
| 25 |
+
if args.seed is not None:
|
| 26 |
+
llm_kwargs["seed"] = args.seed
|
| 27 |
+
return LLM(**llm_kwargs)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def build_sampling_params(args: argparse.Namespace) -> Any:
|
| 31 |
+
from vllm import SamplingParams
|
| 32 |
+
|
| 33 |
+
return SamplingParams(
|
| 34 |
+
temperature=args.temperature,
|
| 35 |
+
top_p=args.top_p,
|
| 36 |
+
top_k=args.top_k,
|
| 37 |
+
max_tokens=args.max_tokens,
|
| 38 |
+
skip_special_tokens=True,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def load_tokenizer(args: argparse.Namespace) -> Any:
|
| 43 |
+
from transformers import AutoTokenizer
|
| 44 |
+
|
| 45 |
+
return AutoTokenizer.from_pretrained(
|
| 46 |
+
args.tokenizer or args.model,
|
| 47 |
+
trust_remote_code=args.trust_remote_code,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def apply_chat_template(tokenizer: Any, messages: list[dict[str, str]], *, enable_thinking: bool) -> str:
|
| 52 |
+
kwargs = {"tokenize": False, "add_generation_prompt": True}
|
| 53 |
+
try:
|
| 54 |
+
return tokenizer.apply_chat_template(messages, enable_thinking=enable_thinking, **kwargs)
|
| 55 |
+
except TypeError as exc:
|
| 56 |
+
message = str(exc)
|
| 57 |
+
if "enable_thinking" not in message and "unexpected" not in message:
|
| 58 |
+
raise
|
| 59 |
+
return tokenizer.apply_chat_template(messages, **kwargs)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def generate_reply(
|
| 63 |
+
*,
|
| 64 |
+
llm: Any,
|
| 65 |
+
tokenizer: Any,
|
| 66 |
+
sampling_params: Any,
|
| 67 |
+
messages: list[dict[str, str]],
|
| 68 |
+
enable_thinking: bool,
|
| 69 |
+
) -> str:
|
| 70 |
+
replies = generate_replies(
|
| 71 |
+
llm=llm,
|
| 72 |
+
tokenizer=tokenizer,
|
| 73 |
+
sampling_params=sampling_params,
|
| 74 |
+
message_batches=[messages],
|
| 75 |
+
enable_thinking=enable_thinking,
|
| 76 |
+
)
|
| 77 |
+
return replies[0] if replies else ""
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def generate_replies(
|
| 81 |
+
*,
|
| 82 |
+
llm: Any,
|
| 83 |
+
tokenizer: Any,
|
| 84 |
+
sampling_params: Any,
|
| 85 |
+
message_batches: list[list[dict[str, str]]],
|
| 86 |
+
enable_thinking: bool,
|
| 87 |
+
) -> list[str]:
|
| 88 |
+
prompts = [
|
| 89 |
+
apply_chat_template(tokenizer, messages, enable_thinking=enable_thinking)
|
| 90 |
+
for messages in message_batches
|
| 91 |
+
]
|
| 92 |
+
request_outputs = llm.generate(prompts, sampling_params, use_tqdm=False)
|
| 93 |
+
replies: list[str] = []
|
| 94 |
+
for request_output in request_outputs:
|
| 95 |
+
if not request_output.outputs:
|
| 96 |
+
replies.append("")
|
| 97 |
+
continue
|
| 98 |
+
replies.append(request_output.outputs[0].text.strip())
|
| 99 |
+
return replies
|
vllm_nanoclaw_runtime/cli.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from .backend import build_llm, build_sampling_params, load_tokenizer
|
| 9 |
+
from .runner import iter_jsonl_results, run_task, run_tasks_batched, utc_now, write_summary
|
| 10 |
+
from .tasks import discover_tasks
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
| 14 |
+
parser = argparse.ArgumentParser(
|
| 15 |
+
description="Run Nanoclaw-compatible workplace tasks with a local vLLM model.",
|
| 16 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 17 |
+
)
|
| 18 |
+
parser.add_argument("--base-tasks", required=True, help="Input base_tasks directory.")
|
| 19 |
+
parser.add_argument("--output", required=True, help="Output result root directory.")
|
| 20 |
+
parser.add_argument("--model", required=True, help="Local model path or model name for vLLM.")
|
| 21 |
+
parser.add_argument("--tokenizer", default=None, help="Tokenizer path; defaults to --model.")
|
| 22 |
+
parser.add_argument(
|
| 23 |
+
"--task-id",
|
| 24 |
+
action="append",
|
| 25 |
+
default=None,
|
| 26 |
+
help="Run only this task id. Can be specified multiple times.",
|
| 27 |
+
)
|
| 28 |
+
parser.add_argument("--task-glob", default="data_*", help="Task directory glob under base_tasks/tasks.")
|
| 29 |
+
parser.add_argument("--overwrite", action="store_true", help="Overwrite existing task result dirs.")
|
| 30 |
+
parser.add_argument("--resume", action="store_true", help="Skip completed task result dirs.")
|
| 31 |
+
parser.add_argument("--run-verifier", action="store_true", help="Run copied verify_workplace.py after inference.")
|
| 32 |
+
parser.add_argument("--verifier-timeout", type=float, default=120.0, help="Verifier timeout in seconds.")
|
| 33 |
+
|
| 34 |
+
thinking = parser.add_mutually_exclusive_group()
|
| 35 |
+
thinking.add_argument("--enable-thinking", dest="enable_thinking", action="store_true")
|
| 36 |
+
thinking.add_argument("--disable-thinking", dest="enable_thinking", action="store_false")
|
| 37 |
+
parser.set_defaults(enable_thinking=False)
|
| 38 |
+
|
| 39 |
+
parser.add_argument("--tensor-parallel-size", type=int, default=1)
|
| 40 |
+
parser.add_argument("--dtype", default="bfloat16", choices=("auto", "float16", "bfloat16", "float32"))
|
| 41 |
+
parser.add_argument("--max-model-len", type=int, default=8192)
|
| 42 |
+
parser.add_argument("--max-num-batched-tokens", type=int, default=None)
|
| 43 |
+
parser.add_argument("--max-num-seqs", type=int, default=None)
|
| 44 |
+
parser.add_argument("--gpu-memory-utilization", type=float, default=0.85)
|
| 45 |
+
parser.add_argument("--trust-remote-code", action=argparse.BooleanOptionalAction, default=True)
|
| 46 |
+
parser.add_argument("--enforce-eager", action="store_true")
|
| 47 |
+
parser.add_argument("--enable-prefix-caching", action="store_true")
|
| 48 |
+
|
| 49 |
+
parser.add_argument("--max-steps", type=int, default=20, help="Maximum agent/tool turns per task.")
|
| 50 |
+
parser.add_argument(
|
| 51 |
+
"--agent-batch-size",
|
| 52 |
+
type=int,
|
| 53 |
+
default=1,
|
| 54 |
+
help="Number of active tasks to advance in each vLLM.generate batch.",
|
| 55 |
+
)
|
| 56 |
+
parser.add_argument("--max-tokens", type=int, default=2048, help="Maximum generated tokens per turn.")
|
| 57 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
| 58 |
+
parser.add_argument("--top-p", type=float, default=0.95)
|
| 59 |
+
parser.add_argument("--top-k", type=int, default=-1)
|
| 60 |
+
parser.add_argument("--seed", type=int, default=None)
|
| 61 |
+
parser.add_argument("--read-limit", type=int, default=24000, help="Maximum characters returned by read.")
|
| 62 |
+
parser.add_argument("--list-limit", type=int, default=500, help="Maximum entries returned by ls/find/grep.")
|
| 63 |
+
parser.add_argument("--allow-python-tool", action="store_true", help="Enable model generated Python execution.")
|
| 64 |
+
parser.add_argument("--python-timeout", type=float, default=20.0, help="run_python timeout in seconds.")
|
| 65 |
+
args = parser.parse_args(argv)
|
| 66 |
+
|
| 67 |
+
if args.max_steps <= 0:
|
| 68 |
+
parser.error("--max-steps must be positive")
|
| 69 |
+
if args.agent_batch_size <= 0:
|
| 70 |
+
parser.error("--agent-batch-size must be positive")
|
| 71 |
+
if args.resume and args.overwrite:
|
| 72 |
+
parser.error("--resume and --overwrite are mutually exclusive")
|
| 73 |
+
return args
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def main(argv: list[str] | None = None) -> int:
|
| 77 |
+
args = parse_args(argv)
|
| 78 |
+
base_tasks = Path(args.base_tasks).expanduser().resolve()
|
| 79 |
+
output_root = Path(args.output).expanduser().resolve()
|
| 80 |
+
requested_task_ids = set(args.task_id) if args.task_id else None
|
| 81 |
+
specs = discover_tasks(base_tasks, task_glob=args.task_glob, task_ids=requested_task_ids)
|
| 82 |
+
|
| 83 |
+
print(f"[info] base_tasks={base_tasks}", file=sys.stderr)
|
| 84 |
+
print(f"[info] output={output_root}", file=sys.stderr)
|
| 85 |
+
print(f"[info] tasks={len(specs)}", file=sys.stderr)
|
| 86 |
+
print(f"[info] model={args.model}", file=sys.stderr)
|
| 87 |
+
print(f"[info] agent_batch_size={args.agent_batch_size}", file=sys.stderr)
|
| 88 |
+
|
| 89 |
+
tokenizer = load_tokenizer(args)
|
| 90 |
+
llm = build_llm(args)
|
| 91 |
+
sampling_params = build_sampling_params(args)
|
| 92 |
+
|
| 93 |
+
started_at = utc_now()
|
| 94 |
+
results: list[dict[str, Any]] = []
|
| 95 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 96 |
+
|
| 97 |
+
if args.agent_batch_size > 1 and len(specs) > 1:
|
| 98 |
+
results = run_tasks_batched(
|
| 99 |
+
specs=specs,
|
| 100 |
+
result_root=output_root,
|
| 101 |
+
llm=llm,
|
| 102 |
+
tokenizer=tokenizer,
|
| 103 |
+
sampling_params=sampling_params,
|
| 104 |
+
args=args,
|
| 105 |
+
)
|
| 106 |
+
(output_root / "results.jsonl").write_text(iter_jsonl_results(results), encoding="utf-8")
|
| 107 |
+
write_summary(output_root, results, started_at)
|
| 108 |
+
else:
|
| 109 |
+
for spec in specs:
|
| 110 |
+
print(f"[task] {spec.task_id}", file=sys.stderr)
|
| 111 |
+
try:
|
| 112 |
+
result = run_task(
|
| 113 |
+
spec=spec,
|
| 114 |
+
result_root=output_root,
|
| 115 |
+
llm=llm,
|
| 116 |
+
tokenizer=tokenizer,
|
| 117 |
+
sampling_params=sampling_params,
|
| 118 |
+
args=args,
|
| 119 |
+
)
|
| 120 |
+
except Exception as exc:
|
| 121 |
+
result = {
|
| 122 |
+
"task_id": spec.task_id,
|
| 123 |
+
"status": "failed",
|
| 124 |
+
"result_dir": str(output_root / spec.task_id),
|
| 125 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 126 |
+
}
|
| 127 |
+
print(f"[error] {spec.task_id}: {result['error']}", file=sys.stderr)
|
| 128 |
+
results.append(result)
|
| 129 |
+
(output_root / "results.jsonl").write_text(iter_jsonl_results(results), encoding="utf-8")
|
| 130 |
+
write_summary(output_root, results, started_at)
|
| 131 |
+
|
| 132 |
+
completed = sum(1 for result in results if result.get("status") == "completed")
|
| 133 |
+
failed = sum(1 for result in results if result.get("status") == "failed")
|
| 134 |
+
skipped = sum(1 for result in results if result.get("status") == "skipped")
|
| 135 |
+
print(f"[done] completed={completed} failed={failed} skipped={skipped} output={output_root}", file=sys.stderr)
|
| 136 |
+
return 1 if failed else 0
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
raise SystemExit(main())
|
vllm_nanoclaw_runtime/prompts.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
TOOL_DESCRIPTIONS: tuple[tuple[str, str], ...] = (
|
| 8 |
+
("read", "Read a text file from the workspace."),
|
| 9 |
+
("write", "Create or replace a text file in the workspace."),
|
| 10 |
+
("edit", "Make a precise in-file text replacement in a workspace file."),
|
| 11 |
+
("apply_patch", "Apply one or more exact text replacements across workspace files."),
|
| 12 |
+
("grep", "Search workspace file contents with a regular expression."),
|
| 13 |
+
("memory_search", "Search MEMORY.md and memory/*.md for relevant prior context."),
|
| 14 |
+
("memory_get", "Read a narrow line range from MEMORY.md or memory/*.md."),
|
| 15 |
+
("memory_append", "Append a note to MEMORY.md or a file under memory/."),
|
| 16 |
+
("find", "Find workspace files by glob pattern."),
|
| 17 |
+
("ls", "List directory contents from the workspace."),
|
| 18 |
+
(
|
| 19 |
+
"exec",
|
| 20 |
+
"Run a shell command in the workspace. Safe read-only commands run directly; other commands follow the configured approval mode.",
|
| 21 |
+
),
|
| 22 |
+
("ask_human_for_confirmation", "Ask the human to approve exactly one command execution."),
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
PYTHON_TOOL_PROMPT = """
|
| 26 |
+
## Local Extension
|
| 27 |
+
|
| 28 |
+
The runner may expose one extra local-only tool when enabled:
|
| 29 |
+
- run_python: Execute Python code inside the workspace.
|
| 30 |
+
|
| 31 |
+
Use run_python only when it is useful for reliable data processing. The code
|
| 32 |
+
runs with the workspace as the current directory. Destructive operations,
|
| 33 |
+
absolute paths, shell commands, subprocess calls, and parent-directory access
|
| 34 |
+
are blocked by the runner.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def build_system_prompt(
|
| 39 |
+
allow_python_tool: bool,
|
| 40 |
+
*,
|
| 41 |
+
workspace_dir: Path | str | None = None,
|
| 42 |
+
model: str | None = None,
|
| 43 |
+
max_steps: int | None = None,
|
| 44 |
+
date_time: str | None = None,
|
| 45 |
+
timezone_name: str | None = None,
|
| 46 |
+
) -> str:
|
| 47 |
+
"""Build a Nanoclaw-compatible system prompt for local vLLM text output.
|
| 48 |
+
|
| 49 |
+
Native Nanoclaw sends OpenAI tool schemas and receives structured
|
| 50 |
+
``tool_calls``. Local vLLM text generation has no native tool-call channel,
|
| 51 |
+
so this prompt keeps Nanoclaw's runtime contract and adds a narrow JSON
|
| 52 |
+
representation for tool calls.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
now = datetime.now().astimezone()
|
| 56 |
+
runtime_date_time = date_time or now.isoformat()
|
| 57 |
+
runtime_timezone = timezone_name or str(now.tzinfo or "UTC")
|
| 58 |
+
runtime_model = model or "local-vllm"
|
| 59 |
+
runtime_max_steps = max_steps if max_steps is not None else "unknown"
|
| 60 |
+
runtime_workspace = str(Path(workspace_dir).resolve()) if workspace_dir is not None else "<task workspace>"
|
| 61 |
+
|
| 62 |
+
chunks = [
|
| 63 |
+
"You are a personal assistant running inside nanoclaw.",
|
| 64 |
+
"nanoclaw implements an experimental OpenClaw-like subset. Follow the provided runtime contract exactly and do not assume unsupported product features exist.",
|
| 65 |
+
"",
|
| 66 |
+
*_tool_prompt_lines(),
|
| 67 |
+
*_tool_call_style_prompt_lines(),
|
| 68 |
+
*_local_vllm_tool_call_prompt_lines(),
|
| 69 |
+
*_memory_recall_prompt_lines(),
|
| 70 |
+
*_workspace_prompt_lines(runtime_workspace),
|
| 71 |
+
*_current_date_time_prompt_lines(runtime_date_time, runtime_timezone),
|
| 72 |
+
*_runtime_prompt_lines(runtime_model, runtime_max_steps),
|
| 73 |
+
]
|
| 74 |
+
if allow_python_tool:
|
| 75 |
+
chunks.append(PYTHON_TOOL_PROMPT.strip())
|
| 76 |
+
chunks.append("")
|
| 77 |
+
return "\n".join(chunks).rstrip() + "\n"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _tool_prompt_lines() -> list[str]:
|
| 81 |
+
lines = [
|
| 82 |
+
"## Tooling",
|
| 83 |
+
"",
|
| 84 |
+
"Tool availability (filtered by policy):",
|
| 85 |
+
"Call tools exactly by the names listed below.",
|
| 86 |
+
"",
|
| 87 |
+
]
|
| 88 |
+
for name, description in TOOL_DESCRIPTIONS:
|
| 89 |
+
lines.append(f"- {name}: {description}")
|
| 90 |
+
lines.append("")
|
| 91 |
+
lines.append(
|
| 92 |
+
"TOOLS.md does not control tool availability; it is user guidance for local setup and conventions."
|
| 93 |
+
)
|
| 94 |
+
lines.append("")
|
| 95 |
+
return lines
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _tool_call_style_prompt_lines() -> list[str]:
|
| 99 |
+
return [
|
| 100 |
+
"## Tool Call Style",
|
| 101 |
+
"",
|
| 102 |
+
"Default: do not narrate routine, low-risk tool calls; just call the tool.",
|
| 103 |
+
"Narrate when it helps: multi-step work, sensitive actions, meaningful uncertainty, or when the user explicitly asks.",
|
| 104 |
+
"Keep narration brief and value-dense.",
|
| 105 |
+
"",
|
| 106 |
+
]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _local_vllm_tool_call_prompt_lines() -> list[str]:
|
| 110 |
+
return [
|
| 111 |
+
"## Local vLLM Tool Call Format",
|
| 112 |
+
"",
|
| 113 |
+
"Native nanoclaw uses OpenAI tool_calls. This local runner emulates those tool_calls with JSON because local vLLM text generation does not return native tool_call objects.",
|
| 114 |
+
"When you want to call tools, output exactly one JSON object and no Markdown fences.",
|
| 115 |
+
"Use relative workspace paths only. Do not use absolute paths or paths containing '..'.",
|
| 116 |
+
"",
|
| 117 |
+
"Single tool call:",
|
| 118 |
+
'{"tool": "read", "arguments": {"path": "data/example.txt"}}',
|
| 119 |
+
"",
|
| 120 |
+
"Multiple tool calls in one assistant turn:",
|
| 121 |
+
'{"actions": [{"tool": "ls", "arguments": {"path": "."}}, {"tool": "read", "arguments": {"path": "data/example.txt"}}]}',
|
| 122 |
+
"",
|
| 123 |
+
"OpenAI-style tool_calls JSON is also accepted:",
|
| 124 |
+
'{"tool_calls": [{"function": {"name": "read", "arguments": "{\\\"path\\\": \\\"data/example.txt\\\"}"}}]}',
|
| 125 |
+
"",
|
| 126 |
+
"When the requested workspace changes are complete, do not call a tool. Reply with the final answer text, exactly like nanoclaw final assistant content without tool_calls.",
|
| 127 |
+
"",
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _memory_recall_prompt_lines() -> list[str]:
|
| 132 |
+
return [
|
| 133 |
+
"## Memory Recall",
|
| 134 |
+
"",
|
| 135 |
+
"Memory recall instructions are disabled for this run by runtime policy.",
|
| 136 |
+
"",
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _workspace_prompt_lines(workspace_dir: str) -> list[str]:
|
| 141 |
+
return [
|
| 142 |
+
"## Workspace",
|
| 143 |
+
"",
|
| 144 |
+
f"Your working directory is: {workspace_dir}",
|
| 145 |
+
"Treat this directory as the primary workspace for file operations unless explicitly instructed otherwise.",
|
| 146 |
+
"All local runner file tools are restricted to this task workspace.",
|
| 147 |
+
"",
|
| 148 |
+
]
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _current_date_time_prompt_lines(date_time: str, timezone_name: str) -> list[str]:
|
| 152 |
+
return [
|
| 153 |
+
"## Current Date & Time",
|
| 154 |
+
"",
|
| 155 |
+
f"Current date/time: {date_time}",
|
| 156 |
+
f"Timezone: {timezone_name}",
|
| 157 |
+
"",
|
| 158 |
+
]
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _runtime_prompt_lines(model: str, max_steps: int | str) -> list[str]:
|
| 162 |
+
return [
|
| 163 |
+
"## Runtime",
|
| 164 |
+
"",
|
| 165 |
+
f"Runtime: model={model} | run_mode=normal | memory_policy=off | max_steps={max_steps}",
|
| 166 |
+
"Command approval: non-read-only exec commands are rejected.",
|
| 167 |
+
"",
|
| 168 |
+
]
|
vllm_nanoclaw_runtime/protocol.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def extract_tool_actions(text: str) -> list[dict[str, Any]]:
|
| 8 |
+
parsed = extract_json_value(text)
|
| 9 |
+
if isinstance(parsed, dict):
|
| 10 |
+
if "actions" in parsed:
|
| 11 |
+
raw_actions = parsed["actions"]
|
| 12 |
+
elif "tool_calls" in parsed:
|
| 13 |
+
raw_actions = parsed["tool_calls"]
|
| 14 |
+
else:
|
| 15 |
+
raw_actions = [parsed]
|
| 16 |
+
elif isinstance(parsed, list):
|
| 17 |
+
raw_actions = parsed
|
| 18 |
+
else:
|
| 19 |
+
raise ValueError("tool call JSON must be an object or array")
|
| 20 |
+
|
| 21 |
+
if not isinstance(raw_actions, list) or not raw_actions:
|
| 22 |
+
raise ValueError("actions must be a non-empty array")
|
| 23 |
+
|
| 24 |
+
actions: list[dict[str, Any]] = []
|
| 25 |
+
for index, raw_action in enumerate(raw_actions, start=1):
|
| 26 |
+
if not isinstance(raw_action, dict):
|
| 27 |
+
raise ValueError(f"action #{index} must be an object")
|
| 28 |
+
actions.append(normalize_tool_action(raw_action))
|
| 29 |
+
return actions
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def normalize_tool_action(raw_action: dict[str, Any]) -> dict[str, Any]:
|
| 33 |
+
if "function" in raw_action and isinstance(raw_action["function"], dict):
|
| 34 |
+
function = raw_action["function"]
|
| 35 |
+
return normalize_named_tool_action(function.get("name"), function.get("arguments", {}))
|
| 36 |
+
if "tool" in raw_action or "name" in raw_action:
|
| 37 |
+
return normalize_named_tool_action(
|
| 38 |
+
raw_action.get("tool", raw_action.get("name")),
|
| 39 |
+
raw_action.get("arguments", {}),
|
| 40 |
+
)
|
| 41 |
+
if "action" in raw_action:
|
| 42 |
+
return dict(raw_action)
|
| 43 |
+
raise ValueError("action object must contain 'tool', 'name', 'function', or 'action'")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def normalize_named_tool_action(name: Any, arguments: Any) -> dict[str, Any]:
|
| 47 |
+
if not isinstance(name, str) or not name.strip():
|
| 48 |
+
raise ValueError("tool name must be a non-empty string")
|
| 49 |
+
if isinstance(arguments, str):
|
| 50 |
+
try:
|
| 51 |
+
arguments = json.loads(arguments) if arguments.strip() else {}
|
| 52 |
+
except json.JSONDecodeError as exc:
|
| 53 |
+
raise ValueError(f"tool arguments are not valid JSON: {exc}") from exc
|
| 54 |
+
if arguments is None:
|
| 55 |
+
arguments = {}
|
| 56 |
+
if not isinstance(arguments, dict):
|
| 57 |
+
raise ValueError("tool arguments must be an object")
|
| 58 |
+
action = dict(arguments)
|
| 59 |
+
action["action"] = name.strip()
|
| 60 |
+
return action
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def extract_json_value(text: str) -> Any:
|
| 64 |
+
stripped = strip_code_fence(text.strip())
|
| 65 |
+
try:
|
| 66 |
+
return json.loads(stripped)
|
| 67 |
+
except json.JSONDecodeError:
|
| 68 |
+
return json.loads(find_first_json_value(stripped))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def strip_code_fence(text: str) -> str:
|
| 72 |
+
if not text.startswith("```"):
|
| 73 |
+
return text
|
| 74 |
+
lines = text.splitlines()
|
| 75 |
+
if len(lines) >= 3 and lines[-1].strip() == "```":
|
| 76 |
+
return "\n".join(lines[1:-1]).strip()
|
| 77 |
+
return text
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def find_first_json_value(text: str) -> str:
|
| 81 |
+
object_start = text.find("{")
|
| 82 |
+
array_start = text.find("[")
|
| 83 |
+
starts = [index for index in (object_start, array_start) if index != -1]
|
| 84 |
+
if not starts:
|
| 85 |
+
raise ValueError("no JSON object or array found")
|
| 86 |
+
start = min(starts)
|
| 87 |
+
opening = text[start]
|
| 88 |
+
closing = "}" if opening == "{" else "]"
|
| 89 |
+
|
| 90 |
+
depth = 0
|
| 91 |
+
in_string = False
|
| 92 |
+
escaped = False
|
| 93 |
+
for index in range(start, len(text)):
|
| 94 |
+
char = text[index]
|
| 95 |
+
if in_string:
|
| 96 |
+
if escaped:
|
| 97 |
+
escaped = False
|
| 98 |
+
elif char == "\\":
|
| 99 |
+
escaped = True
|
| 100 |
+
elif char == '"':
|
| 101 |
+
in_string = False
|
| 102 |
+
continue
|
| 103 |
+
|
| 104 |
+
if char == '"':
|
| 105 |
+
in_string = True
|
| 106 |
+
elif char == opening:
|
| 107 |
+
depth += 1
|
| 108 |
+
elif char == closing:
|
| 109 |
+
depth -= 1
|
| 110 |
+
if depth == 0:
|
| 111 |
+
return text[start : index + 1]
|
| 112 |
+
raise ValueError("unterminated JSON value")
|
vllm_nanoclaw_runtime/run_qwen3_5_27b_nanoclaw_runtime_eager.sh
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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m_nanoclaw_runtime 项目目录内,可以直接启动整个项目;
|
| 5 |
+
# 2) 环境安装与关键 NPU/vLLM 参数沿用之前能跑通的 eager 脚本;
|
| 6 |
+
# 3) 推理入口为 python3 -m vllm_nanoclaw_runtime.cli,不依赖外层 wrapper;
|
| 7 |
+
# 4) 默认输入为项目父目录下的 “数据示例”,输出到项目父目录下 result_nanoclaw_vllm;
|
| 8 |
+
# 5) 默认 TP=4,只用 0,1,2,3 四张卡;如需 8 卡,手动传 TP=8 ASCEND_RT_VISIBLE_DEVICES=0,1,2,3,4,5,6,7。
|
| 9 |
+
|
| 10 |
+
set -xeo pipefail
|
| 11 |
+
|
| 12 |
+
SCRIPT_VERSION="qwen3.5-27b-vllm-nanoclaw-runtime-eager-0610-v1"
|
| 13 |
+
echo "========== ${SCRIPT_VERSION} =========="
|
| 14 |
+
|
| 15 |
+
# ================= 当前项目路径 =================
|
| 16 |
+
# RUNTIME_DIR 是本脚本所在目录,也就是 vllm_nanoclaw_runtime 项目目录。
|
| 17 |
+
# PROJECT_ROOT 默认是它的父目录,用于让 python -m 能 import vllm_nanoclaw_runtime。
|
| 18 |
+
RUNTIME_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
| 19 |
+
PROJECT_ROOT=${PROJECT_ROOT:-$(cd "${RUNTIME_DIR}/.." && pwd)}
|
| 20 |
+
|
| 21 |
+
# ================= 基础路径:沿用之前能跑通的 eager 环境 =================
|
| 22 |
+
WORK_DIR=${WORK_DIR:-/opt/huawei/dataset/zyr_yuyin/lyf/verl-06-08/verl}
|
| 23 |
+
SCRIPT_DIR=${SCRIPT_DIR:-${PROJECT_ROOT}}
|
| 24 |
+
INSTALL_DIR=${INSTALL_DIR:-/home/ma-user}
|
| 25 |
+
BKGS=${BKGS:-/opt/huawei/dataset/zyr_yuyin/bkgs}
|
| 26 |
+
VLLM_LATEST_PKGS=${VLLM_LATEST_PKGS:-/opt/huawei/dataset/zyr_yuyin/lyf/verl-05-12/verl_new_26_05_09/pkgs}
|
| 27 |
+
CANN_BKGS=${CANN_BKGS:-/opt/huawei/dataset/zyr_yuyin/lyf/vllm_bkgs_1015}
|
| 28 |
+
|
| 29 |
+
MODEL_PATH=${MODEL_PATH:-/opt/huawei/dataset/zyr_yuyin/models/Qwen/Qwen3___5-27B}
|
| 30 |
+
BASE_TASKS=${BASE_TASKS:-${SCRIPT_DIR}/数据示例}
|
| 31 |
+
RESULT_ROOT=${RESULT_ROOT:-${SCRIPT_DIR}/result_nanoclaw_vllm}
|
| 32 |
+
RUNNER_MODULE=${RUNNER_MODULE:-vllm_nanoclaw_runtime.cli}
|
| 33 |
+
|
| 34 |
+
GCC_INSTALL_PREFIX=${GCC_INSTALL_PREFIX:-/home/ma-user/gcc-11.3.0}
|
| 35 |
+
COMPILED_GCC_ARCHIVE_PATH=${COMPILED_GCC_ARCHIVE_PATH:-/opt/huawei/dataset/zyr_yuyin/bkgs/gcc-11.3.0-compiled-aarch64.tar.gz}
|
| 36 |
+
|
| 37 |
+
# 第一次跑或环境不确定时保持默认 1;如果环境已经装好,可 SETUP_ENV=0 跳过安装段。
|
| 38 |
+
SETUP_ENV=${SETUP_ENV:-1}
|
| 39 |
+
|
| 40 |
+
chmod 755 "${INSTALL_DIR}" || true
|
| 41 |
+
mkdir -p "${RESULT_ROOT}"
|
| 42 |
+
|
| 43 |
+
# ================= NPU 基础信息 =================
|
| 44 |
+
npu-smi info || true
|
| 45 |
+
|
| 46 |
+
if [ "${SETUP_ENV}" = "1" ]; then
|
| 47 |
+
# ================= Python / 基础包 =================
|
| 48 |
+
pip install --upgrade pip
|
| 49 |
+
pip uninstall -y moxing-framework || true
|
| 50 |
+
|
| 51 |
+
# ================= GCC 11.3.0 =================
|
| 52 |
+
echo "--> 正在从缓存恢复 GCC 11.3.0..."
|
| 53 |
+
tar -xzf "${COMPILED_GCC_ARCHIVE_PATH}" -C /home/ma-user/
|
| 54 |
+
export PATH=${GCC_INSTALL_PREFIX}/bin:${PATH}
|
| 55 |
+
export LD_LIBRARY_PATH=${GCC_INSTALL_PREFIX}/lib64:${GCC_INSTALL_PREFIX}/lib:${LD_LIBRARY_PATH:-}
|
| 56 |
+
export CC=${GCC_INSTALL_PREFIX}/bin/gcc
|
| 57 |
+
export CXX=${GCC_INSTALL_PREFIX}/bin/g++
|
| 58 |
+
echo "--> 验证 GCC 版本:"
|
| 59 |
+
gcc --version
|
| 60 |
+
|
| 61 |
+
# ================= 准备安装包 =================
|
| 62 |
+
cd "${BKGS}"
|
| 63 |
+
cp jemalloc-5.3.0.tar.bz2 "${INSTALL_DIR}" || true
|
| 64 |
+
|
| 65 |
+
rm -rf "${INSTALL_DIR}/vllm" "${INSTALL_DIR}/vllm-ascend"
|
| 66 |
+
cp -r "${VLLM_LATEST_PKGS}/vllm" "${INSTALL_DIR}"
|
| 67 |
+
cp -r "${VLLM_LATEST_PKGS}/vllm-ascend" "${INSTALL_DIR}"
|
| 68 |
+
|
| 69 |
+
cp "${CANN_BKGS}/Ascend-cann-toolkit_8.5.0_linux-aarch64.run" "${INSTALL_DIR}"
|
| 70 |
+
cp "${CANN_BKGS}/Ascend-cann-910b-ops_8.5.0_linux-aarch64.run" "${INSTALL_DIR}"
|
| 71 |
+
cp "${CANN_BKGS}/Ascend-cann-nnal_8.5.0_linux-aarch64.run" "${INSTALL_DIR}"
|
| 72 |
+
|
| 73 |
+
# ================= 安装 CANN / NNAL =================
|
| 74 |
+
echo "################"
|
| 75 |
+
echo "## set ascend env"
|
| 76 |
+
echo "################"
|
| 77 |
+
|
| 78 |
+
cd "${INSTALL_DIR}"
|
| 79 |
+
|
| 80 |
+
chmod +x Ascend-cann-toolkit_8.5.0_linux-aarch64.run
|
| 81 |
+
bash Ascend-cann-toolkit_8.5.0_linux-aarch64.run --install --quiet
|
| 82 |
+
source "${INSTALL_DIR}/Ascend/ascend-toolkit/set_env.sh"
|
| 83 |
+
|
| 84 |
+
chmod +x Ascend-cann-910b-ops_8.5.0_linux-aarch64.run
|
| 85 |
+
bash Ascend-cann-910b-ops_8.5.0_linux-aarch64.run --install --quiet
|
| 86 |
+
|
| 87 |
+
chmod +x Ascend-cann-nnal_8.5.0_linux-aarch64.run
|
| 88 |
+
bash Ascend-cann-nnal_8.5.0_linux-aarch64.run --install --quiet
|
| 89 |
+
source "${INSTALL_DIR}/Ascend/nnal/atb/set_env.sh"
|
| 90 |
+
|
| 91 |
+
export ASCEND_HOME_PATH=${ASCEND_TOOLKIT_HOME}
|
| 92 |
+
export LD_LIBRARY_PATH=/usr/local/Ascend/driver/lib64:/usr/local/Ascend/driver/lib64/common:${LD_LIBRARY_PATH:-}
|
| 93 |
+
echo "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
|
| 94 |
+
|
| 95 |
+
# ================= 安装 PyTorch / torch-npu =================
|
| 96 |
+
pip3 install torch==2.9.0
|
| 97 |
+
pip3 install pyyaml setuptools
|
| 98 |
+
pip3 install torch-npu==2.9.0
|
| 99 |
+
pip3 install torchvision==0.24.0 torchaudio==2.9.0
|
| 100 |
+
|
| 101 |
+
ASCEND_TOOLKIT_PYTHON_PATH=/home/ma-user/Ascend/ascend-toolkit/latest/python/site-packages
|
| 102 |
+
export PYTHONPATH=${PYTHONPATH:-}:${INSTALL_DIR}:${ASCEND_TOOLKIT_PYTHON_PATH}
|
| 103 |
+
pip install pybind11==2.13.6
|
| 104 |
+
|
| 105 |
+
# ================= 安装 vLLM / vLLM-Ascend =================
|
| 106 |
+
cd "${INSTALL_DIR}/vllm"
|
| 107 |
+
VLLM_TARGET_DEVICE=empty pip install .
|
| 108 |
+
|
| 109 |
+
cd "${INSTALL_DIR}/vllm-ascend"
|
| 110 |
+
pip install -e .
|
| 111 |
+
|
| 112 |
+
# ================= 可选 jemalloc:默认关闭,避免额外编译耗时 =================
|
| 113 |
+
INSTALL_JEMALLOC=${INSTALL_JEMALLOC:-0}
|
| 114 |
+
if [ "${INSTALL_JEMALLOC}" = "1" ]; then
|
| 115 |
+
cd "${INSTALL_DIR}"
|
| 116 |
+
tar -xvf jemalloc-5.3.0.tar.bz2
|
| 117 |
+
cd jemalloc-5.3.0
|
| 118 |
+
./configure --prefix="${INSTALL_DIR}"
|
| 119 |
+
make -j"$(nproc)"
|
| 120 |
+
make install
|
| 121 |
+
export LD_PRELOAD=${INSTALL_DIR}/lib/libjemalloc.so.2:${LD_PRELOAD:-}
|
| 122 |
+
fi
|
| 123 |
+
|
| 124 |
+
# ================= 安装 Triton-Ascend 3.2.1 =================
|
| 125 |
+
pip install --no-deps /opt/huawei/dataset/zyr_yuyin/bkgs/triton_ascend-3.2.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl
|
| 126 |
+
|
| 127 |
+
# ================= 安装 VERL 依赖:沿用之前环境,主要提供 transformers/tokenizer 等 =================
|
| 128 |
+
cd "${WORK_DIR}"
|
| 129 |
+
pip install -r requirements-npu.txt
|
| 130 |
+
pip install -e .
|
| 131 |
+
pip install --upgrade 'urllib3==1.26.11'
|
| 132 |
+
pip install loguru
|
| 133 |
+
pip install tree_sitter==0.21.3
|
| 134 |
+
pip install tree-sitter-java==0.21.0
|
| 135 |
+
pip install tree-sitter-javascript==0.21.4
|
| 136 |
+
|
| 137 |
+
ACL_PATH=/home/ma-user/Ascend/ascend-toolkit/latest/aarch64-linux/lib64
|
| 138 |
+
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${ACL_PATH}
|
| 139 |
+
echo "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
|
| 140 |
+
|
| 141 |
+
pip uninstall -y transformers || true
|
| 142 |
+
pip install transformers==5.3.0
|
| 143 |
+
pip install accelerate==1.13.0 mathruler
|
| 144 |
+
pip install jsonargparse
|
| 145 |
+
pip install deepdiff sympy html2text requests bs4 mpmath swanlab PandoraBox json_repair
|
| 146 |
+
pip list
|
| 147 |
+
else
|
| 148 |
+
# 环境已经装好时,仍然尝试 source CANN/NNAL 环境。
|
| 149 |
+
if [ -f "${INSTALL_DIR}/Ascend/ascend-toolkit/set_env.sh" ]; then
|
| 150 |
+
source "${INSTALL_DIR}/Ascend/ascend-toolkit/set_env.sh"
|
| 151 |
+
fi
|
| 152 |
+
if [ -f "${INSTALL_DIR}/Ascend/nnal/atb/set_env.sh" ]; then
|
| 153 |
+
source "${INSTALL_DIR}/Ascend/nnal/atb/set_env.sh"
|
| 154 |
+
fi
|
| 155 |
+
export PATH=${GCC_INSTALL_PREFIX}/bin:${PATH}
|
| 156 |
+
export LD_LIBRARY_PATH=${GCC_INSTALL_PREFIX}/lib64:${GCC_INSTALL_PREFIX}/lib:${LD_LIBRARY_PATH:-}
|
| 157 |
+
export PYTHONPATH=${PYTHONPATH:-}:${INSTALL_DIR}:/home/ma-user/Ascend/ascend-toolkit/latest/python/site-packages
|
| 158 |
+
export ASCEND_HOME_PATH=${ASCEND_TOOLKIT_HOME:-/home/ma-user/Ascend/ascend-toolkit/latest}
|
| 159 |
+
export LD_LIBRARY_PATH=/usr/local/Ascend/driver/lib64:/usr/local/Ascend/driver/lib64/common:${LD_LIBRARY_PATH:-}
|
| 160 |
+
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/home/ma-user/Ascend/ascend-toolkit/latest/aarch64-linux/lib64
|
| 161 |
+
fi
|
| 162 |
+
|
| 163 |
+
# ================= PLOG:兼容 ModelArts 环境;非 ModelArts 也能跑 =================
|
| 164 |
+
if [ -n "${MA_VJ_NAME:-}" ] && [ -n "${VC_TASK_INDEX:-}" ] && [ -n "${MA_LOG_DIR:-}" ]; then
|
| 165 |
+
ma_vj_name=$(echo "${MA_VJ_NAME}" | sed 's:ma-job:modelarts-job:g')
|
| 166 |
+
task_name=worker-${VC_TASK_INDEX}
|
| 167 |
+
task_plog_path=${MA_LOG_DIR}/${ma_vj_name}/${task_name}
|
| 168 |
+
mkdir -p "${task_plog_path}"
|
| 169 |
+
export ASCEND_PROCESS_LOG_PATH=${task_plog_path}/${VC_TASK_INDEX}
|
| 170 |
+
else
|
| 171 |
+
export ASCEND_PROCESS_LOG_PATH=${ASCEND_PROCESS_LOG_PATH:-${SCRIPT_DIR}/plog_nanoclaw_vllm}
|
| 172 |
+
mkdir -p "${ASCEND_PROCESS_LOG_PATH}"
|
| 173 |
+
fi
|
| 174 |
+
echo "plog path: ${ASCEND_PROCESS_LOG_PATH}"
|
| 175 |
+
|
| 176 |
+
# ================= 单机 vLLM/HCCL 环境:沿用可运行 eager 配置 =================
|
| 177 |
+
cd "${PROJECT_ROOT}"
|
| 178 |
+
export PYTHONPATH=${PROJECT_ROOT}:${PYTHONPATH:-}
|
| 179 |
+
|
| 180 |
+
export ASCEND_RT_VISIBLE_DEVICES=${ASCEND_RT_VISIBLE_DEVICES:-0,1,2,3}
|
| 181 |
+
export OMP_NUM_THREADS=${OMP_NUM_THREADS:-1}
|
| 182 |
+
export TOKENIZERS_PARALLELISM=false
|
| 183 |
+
export PYTHONUNBUFFERED=1
|
| 184 |
+
export ASCEND_GLOBAL_LOG_LEVEL=${ASCEND_GLOBAL_LOG_LEVEL:-3}
|
| 185 |
+
|
| 186 |
+
export VLLM_LOGGING_LEVEL=${VLLM_LOGGING_LEVEL:-INFO}
|
| 187 |
+
export VLLM_USE_V1=${VLLM_USE_V1:-1}
|
| 188 |
+
export VLLM_ENABLE_V1_MULTIPROCESSING=${VLLM_ENABLE_V1_MULTIPROCESSING:-0}
|
| 189 |
+
export VLLM_ASCEND_ENABLE_NZ=${VLLM_ASCEND_ENABLE_NZ:-0}
|
| 190 |
+
export VLLM_ENGINE_ITERATION_TIMEOUT_S=${VLLM_ENGINE_ITERATION_TIMEOUT_S:-3600}
|
| 191 |
+
export VLLM_WORKER_MULTIPROC_METHOD=${VLLM_WORKER_MULTIPROC_METHOD:-spawn}
|
| 192 |
+
|
| 193 |
+
# eager 兜底:规避 profile_run / torch.compile / TorchDynamo 相关问题。
|
| 194 |
+
export TORCHDYNAMO_DISABLE=${TORCHDYNAMO_DISABLE:-1}
|
| 195 |
+
export TORCH_COMPILE_DISABLE=${TORCH_COMPILE_DISABLE:-1}
|
| 196 |
+
|
| 197 |
+
export HCCL_CONNECT_TIMEOUT=${HCCL_CONNECT_TIMEOUT:-3600}
|
| 198 |
+
export HCCL_EXEC_TIMEOUT=${HCCL_EXEC_TIMEOUT:-3600}
|
| 199 |
+
export HCCL_EVENT_TIMEOUT=${HCCL_EVENT_TIMEOUT:-7200}
|
| 200 |
+
export HCCL_BUFFSIZE=${HCCL_BUFFSIZE:-8}
|
| 201 |
+
export P2P_HCCL_BUFFSIZE=${P2P_HCCL_BUFFSIZE:-16}
|
| 202 |
+
export HCCL_OP_EXPANSION_MODE=${HCCL_OP_EXPANSION_MODE:-AIV}
|
| 203 |
+
export HCCL_ASYNC_ERROR_HANDLING=${HCCL_ASYNC_ERROR_HANDLING:-0}
|
| 204 |
+
|
| 205 |
+
export TASK_QUEUE_ENABLE=${TASK_QUEUE_ENABLE:-1}
|
| 206 |
+
export COMBINED_ENABLE=${COMBINED_ENABLE:-1}
|
| 207 |
+
export CLOSE_MATMUL_K_SHIFT=${CLOSE_MATMUL_K_SHIFT:-1}
|
| 208 |
+
export ATB_MATMUL_SHUFFLE_K_ENABLE=${ATB_MATMUL_SHUFFLE_K_ENABLE:-0}
|
| 209 |
+
export PYTORCH_NPU_ALLOC_CONF=${PYTORCH_NPU_ALLOC_CONF:-expandable_segments:True}
|
| 210 |
+
|
| 211 |
+
ulimit -n 65536 || true
|
| 212 |
+
npu-smi info || true
|
| 213 |
+
|
| 214 |
+
# ================= vLLM / agent 参数 =================
|
| 215 |
+
TP=${TP:-4}
|
| 216 |
+
DTYPE=${DTYPE:-bfloat16}
|
| 217 |
+
MAX_MODEL_LEN=${MAX_MODEL_LEN:-262144}
|
| 218 |
+
MAX_NUM_BATCHED_TOKENS=${MAX_NUM_BATCHED_TOKENS:-32768}
|
| 219 |
+
MAX_NUM_SEQS=${MAX_NUM_SEQS:-512}
|
| 220 |
+
GPU_MEMORY_UTILIZATION=${GPU_MEMORY_UTILIZATION:-0.70}
|
| 221 |
+
|
| 222 |
+
MAX_STEPS=${MAX_STEPS:-20}
|
| 223 |
+
AGENT_BATCH_SIZE=${AGENT_BATCH_SIZE:-8}
|
| 224 |
+
MAX_TOKENS=${MAX_TOKENS:-2048}
|
| 225 |
+
TEMPERATURE=${TEMPERATURE:-0.2}
|
| 226 |
+
TOP_P=${TOP_P:-0.95}
|
| 227 |
+
TOP_K=${TOP_K:--1}
|
| 228 |
+
DISABLE_THINKING=${DISABLE_THINKING:-1}
|
| 229 |
+
RESUME=${RESUME:-0}
|
| 230 |
+
OVERWRITE=${OVERWRITE:-1}
|
| 231 |
+
ENFORCE_EAGER=${ENFORCE_EAGER:-1}
|
| 232 |
+
ENABLE_PREFIX_CACHING=${ENABLE_PREFIX_CACHING:-0}
|
| 233 |
+
RUN_VERIFIER=${RUN_VERIFIER:-0}
|
| 234 |
+
ALLOW_PYTHON_TOOL=${ALLOW_PYTHON_TOOL:-0}
|
| 235 |
+
PYTHON_TIMEOUT=${PYTHON_TIMEOUT:-20}
|
| 236 |
+
VERIFIER_TIMEOUT=${VERIFIER_TIMEOUT:-120}
|
| 237 |
+
|
| 238 |
+
# 可选:只跑某些任务。多个任务用逗号分隔,如 TASK_IDS=data_1487,data_0002。
|
| 239 |
+
TASK_IDS=${TASK_IDS:-}
|
| 240 |
+
TASK_GLOB=${TASK_GLOB:-data_*}
|
| 241 |
+
|
| 242 |
+
if [ ! -f "${RUNTIME_DIR}/cli.py" ]; then
|
| 243 |
+
echo "ERROR: vllm_nanoclaw_runtime cli.py not found: ${RUNTIME_DIR}/cli.py" >&2
|
| 244 |
+
exit 2
|
| 245 |
+
fi
|
| 246 |
+
|
| 247 |
+
if [ ! -d "${BASE_TASKS}" ]; then
|
| 248 |
+
echo "ERROR: BASE_TASKS directory not found: ${BASE_TASKS}" >&2
|
| 249 |
+
exit 2
|
| 250 |
+
fi
|
| 251 |
+
|
| 252 |
+
mkdir -p "${RESULT_ROOT}"
|
| 253 |
+
|
| 254 |
+
args=(
|
| 255 |
+
--base-tasks "${BASE_TASKS}"
|
| 256 |
+
--output "${RESULT_ROOT}"
|
| 257 |
+
--model "${MODEL_PATH}"
|
| 258 |
+
--task-glob "${TASK_GLOB}"
|
| 259 |
+
--tensor-parallel-size "${TP}"
|
| 260 |
+
--dtype "${DTYPE}"
|
| 261 |
+
--max-model-len "${MAX_MODEL_LEN}"
|
| 262 |
+
--max-num-batched-tokens "${MAX_NUM_BATCHED_TOKENS}"
|
| 263 |
+
--max-num-seqs "${MAX_NUM_SEQS}"
|
| 264 |
+
--gpu-memory-utilization "${GPU_MEMORY_UTILIZATION}"
|
| 265 |
+
--max-steps "${MAX_STEPS}"
|
| 266 |
+
--agent-batch-size "${AGENT_BATCH_SIZE}"
|
| 267 |
+
--max-tokens "${MAX_TOKENS}"
|
| 268 |
+
--temperature "${TEMPERATURE}"
|
| 269 |
+
--top-p "${TOP_P}"
|
| 270 |
+
--top-k "${TOP_K}"
|
| 271 |
+
--python-timeout "${PYTHON_TIMEOUT}"
|
| 272 |
+
--verifier-timeout "${VERIFIER_TIMEOUT}"
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
if [ -n "${TASK_IDS}" ]; then
|
| 276 |
+
IFS=',' read -ra task_id_array <<< "${TASK_IDS}"
|
| 277 |
+
for task_id in "${task_id_array[@]}"; do
|
| 278 |
+
task_id_trimmed=$(echo "${task_id}" | xargs)
|
| 279 |
+
if [ -n "${task_id_trimmed}" ]; then
|
| 280 |
+
args+=(--task-id "${task_id_trimmed}")
|
| 281 |
+
fi
|
| 282 |
+
done
|
| 283 |
+
fi
|
| 284 |
+
|
| 285 |
+
if [ "${DISABLE_THINKING}" = "1" ] || [ "${DISABLE_THINKING}" = "true" ] || [ "${DISABLE_THINKING}" = "True" ]; then
|
| 286 |
+
args+=(--disable-thinking)
|
| 287 |
+
else
|
| 288 |
+
args+=(--enable-thinking)
|
| 289 |
+
fi
|
| 290 |
+
|
| 291 |
+
if [ "${RESUME}" = "1" ] || [ "${RESUME}" = "true" ] || [ "${RESUME}" = "True" ]; then
|
| 292 |
+
args+=(--resume)
|
| 293 |
+
elif [ "${OVERWRITE}" = "1" ] || [ "${OVERWRITE}" = "true" ] || [ "${OVERWRITE}" = "True" ]; then
|
| 294 |
+
args+=(--overwrite)
|
| 295 |
+
fi
|
| 296 |
+
|
| 297 |
+
if [ "${ENFORCE_EAGER}" = "1" ] || [ "${ENFORCE_EAGER}" = "true" ] || [ "${ENFORCE_EAGER}" = "True" ]; then
|
| 298 |
+
args+=(--enforce-eager)
|
| 299 |
+
fi
|
| 300 |
+
|
| 301 |
+
if [ "${ENABLE_PREFIX_CACHING}" = "1" ] || [ "${ENABLE_PREFIX_CACHING}" = "true" ] || [ "${ENABLE_PREFIX_CACHING}" = "True" ]; then
|
| 302 |
+
args+=(--enable-prefix-caching)
|
| 303 |
+
fi
|
| 304 |
+
|
| 305 |
+
if [ "${RUN_VERIFIER}" = "1" ] || [ "${RUN_VERIFIER}" = "true" ] || [ "${RUN_VERIFIER}" = "True" ]; then
|
| 306 |
+
args+=(--run-verifier)
|
| 307 |
+
fi
|
| 308 |
+
|
| 309 |
+
if [ "${ALLOW_PYTHON_TOOL}" = "1" ] || [ "${ALLOW_PYTHON_TOOL}" = "true" ] || [ "${ALLOW_PYTHON_TOOL}" = "True" ]; then
|
| 310 |
+
args+=(--allow-python-tool)
|
| 311 |
+
fi
|
| 312 |
+
|
| 313 |
+
cat <<INFO
|
| 314 |
+
========== vLLM Nanoclaw-like eager runner config ==========
|
| 315 |
+
SCRIPT_VERSION=${SCRIPT_VERSION}
|
| 316 |
+
SCRIPT_DIR=${SCRIPT_DIR}
|
| 317 |
+
RUNTIME_DIR=${RUNTIME_DIR}
|
| 318 |
+
PROJECT_ROOT=${PROJECT_ROOT}
|
| 319 |
+
RUNNER_MODULE=${RUNNER_MODULE}
|
| 320 |
+
BASE_TASKS=${BASE_TASKS}
|
| 321 |
+
RESULT_ROOT=${RESULT_ROOT}
|
| 322 |
+
MODEL_PATH=${MODEL_PATH}
|
| 323 |
+
ASCEND_RT_VISIBLE_DEVICES=${ASCEND_RT_VISIBLE_DEVICES}
|
| 324 |
+
TP=${TP}
|
| 325 |
+
DTYPE=${DTYPE}
|
| 326 |
+
MAX_MODEL_LEN=${MAX_MODEL_LEN}
|
| 327 |
+
MAX_NUM_BATCHED_TOKENS=${MAX_NUM_BATCHED_TOKENS}
|
| 328 |
+
MAX_NUM_SEQS=${MAX_NUM_SEQS}
|
| 329 |
+
GPU_MEMORY_UTILIZATION=${GPU_MEMORY_UTILIZATION}
|
| 330 |
+
MAX_STEPS=${MAX_STEPS}
|
| 331 |
+
AGENT_BATCH_SIZE=${AGENT_BATCH_SIZE}
|
| 332 |
+
MAX_TOKENS=${MAX_TOKENS}
|
| 333 |
+
TEMPERATURE=${TEMPERATURE}
|
| 334 |
+
TOP_P=${TOP_P}
|
| 335 |
+
TOP_K=${TOP_K}
|
| 336 |
+
DISABLE_THINKING=${DISABLE_THINKING}
|
| 337 |
+
ENFORCE_EAGER=${ENFORCE_EAGER}
|
| 338 |
+
ENABLE_PREFIX_CACHING=${ENABLE_PREFIX_CACHING}
|
| 339 |
+
RUN_VERIFIER=${RUN_VERIFIER}
|
| 340 |
+
ALLOW_PYTHON_TOOL=${ALLOW_PYTHON_TOOL}
|
| 341 |
+
TASK_IDS=${TASK_IDS}
|
| 342 |
+
TASK_GLOB=${TASK_GLOB}
|
| 343 |
+
SETUP_ENV=${SETUP_ENV}
|
| 344 |
+
VLLM_USE_V1=${VLLM_USE_V1}
|
| 345 |
+
VLLM_ENABLE_V1_MULTIPROCESSING=${VLLM_ENABLE_V1_MULTIPROCESSING}
|
| 346 |
+
VLLM_WORKER_MULTIPROC_METHOD=${VLLM_WORKER_MULTIPROC_METHOD}
|
| 347 |
+
TORCHDYNAMO_DISABLE=${TORCHDYNAMO_DISABLE}
|
| 348 |
+
TORCH_COMPILE_DISABLE=${TORCH_COMPILE_DISABLE}
|
| 349 |
+
HCCL_BUFFSIZE=${HCCL_BUFFSIZE}
|
| 350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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import shutil
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
from collections.abc import Iterable
|
| 10 |
+
from datetime import datetime, timezone
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
from .backend import generate_reply, generate_replies
|
| 15 |
+
from .prompts import build_system_prompt
|
| 16 |
+
from .protocol import extract_tool_actions
|
| 17 |
+
from .tools import execute_actions, workspace_subprocess_env
|
| 18 |
+
from .types import TaskRunState, TaskSpec
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def utc_now() -> str:
|
| 22 |
+
return datetime.now(timezone.utc).isoformat()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def run_task(
|
| 26 |
+
*,
|
| 27 |
+
spec: TaskSpec,
|
| 28 |
+
result_root: Path,
|
| 29 |
+
llm: Any,
|
| 30 |
+
tokenizer: Any,
|
| 31 |
+
sampling_params: Any,
|
| 32 |
+
args: argparse.Namespace,
|
| 33 |
+
) -> dict[str, Any]:
|
| 34 |
+
prepared = prepare_task_run_state(spec=spec, result_root=result_root, args=args)
|
| 35 |
+
if isinstance(prepared, dict):
|
| 36 |
+
return prepared
|
| 37 |
+
|
| 38 |
+
state = prepared
|
| 39 |
+
try:
|
| 40 |
+
while state.status == "running" and state.steps_used < args.max_steps:
|
| 41 |
+
reply = generate_reply(
|
| 42 |
+
llm=llm,
|
| 43 |
+
tokenizer=tokenizer,
|
| 44 |
+
sampling_params=sampling_params,
|
| 45 |
+
messages=state.messages,
|
| 46 |
+
enable_thinking=args.enable_thinking,
|
| 47 |
+
)
|
| 48 |
+
process_task_reply(state, reply, args=args)
|
| 49 |
+
except Exception as exc:
|
| 50 |
+
state.status = "failed"
|
| 51 |
+
state.error = f"{type(exc).__name__}: {exc}"
|
| 52 |
+
state.events.append({"step": state.steps_used + 1, "error": state.error})
|
| 53 |
+
write_task_state_history(state)
|
| 54 |
+
raise
|
| 55 |
+
|
| 56 |
+
return finalize_task_state(state, args=args)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def prepare_task_run_state(
|
| 60 |
+
*,
|
| 61 |
+
spec: TaskSpec,
|
| 62 |
+
result_root: Path,
|
| 63 |
+
args: argparse.Namespace,
|
| 64 |
+
) -> TaskRunState | dict[str, Any]:
|
| 65 |
+
result_dir = result_root / spec.task_id
|
| 66 |
+
if result_dir.exists():
|
| 67 |
+
if args.overwrite:
|
| 68 |
+
shutil.rmtree(result_dir)
|
| 69 |
+
elif args.resume and is_completed_result(result_dir):
|
| 70 |
+
print(f"[skip] {spec.task_id}: completed result exists at {result_dir}", file=sys.stderr)
|
| 71 |
+
return {"task_id": spec.task_id, "status": "skipped", "result_dir": str(result_dir)}
|
| 72 |
+
else:
|
| 73 |
+
raise FileExistsError(f"result dir already exists: {result_dir}; pass --overwrite or --resume")
|
| 74 |
+
|
| 75 |
+
result_dir.mkdir(parents=True, exist_ok=False)
|
| 76 |
+
workspace_after = result_dir / "workspace_after"
|
| 77 |
+
workspace_before = result_dir / "workspace_before"
|
| 78 |
+
workspace_after.mkdir(parents=True, exist_ok=False)
|
| 79 |
+
|
| 80 |
+
prompt_text = spec.prompt_path.read_text(encoding="utf-8")
|
| 81 |
+
shutil.copy2(spec.prompt_path, result_dir / "task_prompt.md")
|
| 82 |
+
if spec.verifier_path is not None:
|
| 83 |
+
shutil.copy2(spec.verifier_path, result_dir / "verify_workplace.py")
|
| 84 |
+
|
| 85 |
+
env_result = run_env_builder(spec.env_builder_path, workspace_after)
|
| 86 |
+
shutil.copytree(workspace_after, workspace_before)
|
| 87 |
+
|
| 88 |
+
messages = build_initial_messages(
|
| 89 |
+
prompt_text=prompt_text,
|
| 90 |
+
workspace_after=workspace_after,
|
| 91 |
+
args=args,
|
| 92 |
+
)
|
| 93 |
+
state = TaskRunState(
|
| 94 |
+
spec=spec,
|
| 95 |
+
result_dir=result_dir,
|
| 96 |
+
workspace_before=workspace_before,
|
| 97 |
+
workspace_after=workspace_after,
|
| 98 |
+
history_path=result_dir / "conversation_history.json",
|
| 99 |
+
metadata_path=result_dir / "runner_metadata.json",
|
| 100 |
+
prompt_text=prompt_text,
|
| 101 |
+
env_result=env_result,
|
| 102 |
+
started_at=utc_now(),
|
| 103 |
+
messages=messages,
|
| 104 |
+
)
|
| 105 |
+
write_task_state_history(state)
|
| 106 |
+
return state
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def build_initial_messages(
|
| 110 |
+
*,
|
| 111 |
+
prompt_text: str,
|
| 112 |
+
workspace_after: Path,
|
| 113 |
+
args: argparse.Namespace,
|
| 114 |
+
) -> list[dict[str, str]]:
|
| 115 |
+
return [
|
| 116 |
+
{
|
| 117 |
+
"role": "system",
|
| 118 |
+
"content": build_system_prompt(
|
| 119 |
+
args.allow_python_tool,
|
| 120 |
+
workspace_dir=workspace_after,
|
| 121 |
+
model=args.model,
|
| 122 |
+
max_steps=args.max_steps,
|
| 123 |
+
),
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"role": "user",
|
| 127 |
+
"content": (
|
| 128 |
+
"Solve this task by using Nanoclaw-compatible tool calls to inspect and modify the workspace.\n"
|
| 129 |
+
"Only provide a final answer after the requested workspace changes are complete.\n\n"
|
| 130 |
+
f"Task:\n{prompt_text}"
|
| 131 |
+
),
|
| 132 |
+
},
|
| 133 |
+
]
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def run_tasks_batched(
|
| 137 |
+
*,
|
| 138 |
+
specs: list[TaskSpec],
|
| 139 |
+
result_root: Path,
|
| 140 |
+
llm: Any,
|
| 141 |
+
tokenizer: Any,
|
| 142 |
+
sampling_params: Any,
|
| 143 |
+
args: argparse.Namespace,
|
| 144 |
+
) -> list[dict[str, Any]]:
|
| 145 |
+
results: list[dict[str, Any]] = []
|
| 146 |
+
states: list[TaskRunState] = []
|
| 147 |
+
|
| 148 |
+
for spec in specs:
|
| 149 |
+
print(f"[prepare] {spec.task_id}", file=sys.stderr)
|
| 150 |
+
try:
|
| 151 |
+
prepared = prepare_task_run_state(spec=spec, result_root=result_root, args=args)
|
| 152 |
+
except Exception as exc:
|
| 153 |
+
result = {
|
| 154 |
+
"task_id": spec.task_id,
|
| 155 |
+
"status": "failed",
|
| 156 |
+
"result_dir": str(result_root / spec.task_id),
|
| 157 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 158 |
+
}
|
| 159 |
+
results.append(result)
|
| 160 |
+
print(f"[error] {spec.task_id}: {result['error']}", file=sys.stderr)
|
| 161 |
+
continue
|
| 162 |
+
|
| 163 |
+
if isinstance(prepared, dict):
|
| 164 |
+
results.append(prepared)
|
| 165 |
+
else:
|
| 166 |
+
states.append(prepared)
|
| 167 |
+
|
| 168 |
+
while True:
|
| 169 |
+
active_states = [state for state in states if state.status == "running"]
|
| 170 |
+
if not active_states:
|
| 171 |
+
break
|
| 172 |
+
|
| 173 |
+
current_batch = active_states[: args.agent_batch_size]
|
| 174 |
+
print(
|
| 175 |
+
"[batch] "
|
| 176 |
+
+ ", ".join(f"{state.spec.task_id}:step{state.steps_used + 1}" for state in current_batch),
|
| 177 |
+
file=sys.stderr,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
try:
|
| 181 |
+
replies = generate_replies(
|
| 182 |
+
llm=llm,
|
| 183 |
+
tokenizer=tokenizer,
|
| 184 |
+
sampling_params=sampling_params,
|
| 185 |
+
message_batches=[state.messages for state in current_batch],
|
| 186 |
+
enable_thinking=args.enable_thinking,
|
| 187 |
+
)
|
| 188 |
+
for state, reply in zip(current_batch, replies, strict=True):
|
| 189 |
+
process_task_reply(state, reply, args=args)
|
| 190 |
+
except Exception as exc:
|
| 191 |
+
error = f"{type(exc).__name__}: {exc}"
|
| 192 |
+
for state in current_batch:
|
| 193 |
+
state.status = "failed"
|
| 194 |
+
state.error = error
|
| 195 |
+
state.events.append({"step": state.steps_used + 1, "error": error})
|
| 196 |
+
write_task_state_history(state)
|
| 197 |
+
|
| 198 |
+
for state in states:
|
| 199 |
+
results.append(finalize_task_state(state, args=args))
|
| 200 |
+
return results
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def process_task_reply(state: TaskRunState, reply: str, *, args: argparse.Namespace) -> None:
|
| 204 |
+
state.steps_used += 1
|
| 205 |
+
step = state.steps_used
|
| 206 |
+
state.messages.append({"role": "assistant", "content": reply})
|
| 207 |
+
|
| 208 |
+
try:
|
| 209 |
+
actions = extract_tool_actions(reply)
|
| 210 |
+
except ValueError as exc:
|
| 211 |
+
if is_final_text_response(reply):
|
| 212 |
+
state.status = "completed"
|
| 213 |
+
state.final_answer = reply.strip()
|
| 214 |
+
state.events.append(
|
| 215 |
+
{
|
| 216 |
+
"step": step,
|
| 217 |
+
"reply": reply,
|
| 218 |
+
"is_final": True,
|
| 219 |
+
"final_response_mode": "plain_text_without_tool_calls",
|
| 220 |
+
}
|
| 221 |
+
)
|
| 222 |
+
write_task_state_history(state)
|
| 223 |
+
return
|
| 224 |
+
|
| 225 |
+
observation = f"Action parse error: {exc}. Output JSON tool_calls/actions or provide a plain final answer only when the task is complete."
|
| 226 |
+
state.events.append({"step": step, "reply": reply, "error": observation})
|
| 227 |
+
if step >= args.max_steps:
|
| 228 |
+
state.status = "failed"
|
| 229 |
+
state.error = f"exceeded max steps ({args.max_steps}) without valid tool call or final answer"
|
| 230 |
+
else:
|
| 231 |
+
state.messages.append({"role": "user", "content": f"Observation:\n{observation}"})
|
| 232 |
+
write_task_state_history(state)
|
| 233 |
+
return
|
| 234 |
+
|
| 235 |
+
action_events, observation, is_final, final_answer = execute_actions(
|
| 236 |
+
actions,
|
| 237 |
+
state.workspace_after,
|
| 238 |
+
args=args,
|
| 239 |
+
step=step,
|
| 240 |
+
)
|
| 241 |
+
state.events.append(
|
| 242 |
+
{
|
| 243 |
+
"step": step,
|
| 244 |
+
"reply": reply,
|
| 245 |
+
"actions": action_events,
|
| 246 |
+
"observation": observation,
|
| 247 |
+
"is_final": is_final,
|
| 248 |
+
}
|
| 249 |
+
)
|
| 250 |
+
if is_final:
|
| 251 |
+
state.status = "completed"
|
| 252 |
+
state.final_answer = final_answer or ""
|
| 253 |
+
write_task_state_history(state)
|
| 254 |
+
return
|
| 255 |
+
|
| 256 |
+
if step >= args.max_steps:
|
| 257 |
+
state.status = "failed"
|
| 258 |
+
state.error = f"exceeded max steps ({args.max_steps}) without final answer"
|
| 259 |
+
else:
|
| 260 |
+
state.messages.append({"role": "user", "content": f"Observation:\n{observation}"})
|
| 261 |
+
write_task_state_history(state)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def is_final_text_response(reply: str) -> bool:
|
| 265 |
+
stripped = reply.strip()
|
| 266 |
+
if not stripped:
|
| 267 |
+
return False
|
| 268 |
+
if stripped.startswith("```"):
|
| 269 |
+
return False
|
| 270 |
+
return stripped[0] not in "[{"
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def finalize_task_state(state: TaskRunState, *, args: argparse.Namespace) -> dict[str, Any]:
|
| 274 |
+
if state.status == "running":
|
| 275 |
+
state.status = "failed"
|
| 276 |
+
state.error = state.error or f"exceeded max steps ({args.max_steps}) without final answer"
|
| 277 |
+
|
| 278 |
+
if args.run_verifier and state.spec.verifier_path is not None:
|
| 279 |
+
state.verifier_result = run_verifier(
|
| 280 |
+
state.result_dir / "verify_workplace.py",
|
| 281 |
+
state.workspace_after,
|
| 282 |
+
timeout=args.verifier_timeout,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
write_task_state_history(state)
|
| 286 |
+
metadata = {
|
| 287 |
+
"task_id": state.spec.task_id,
|
| 288 |
+
"status": state.status,
|
| 289 |
+
"error": state.error,
|
| 290 |
+
"final_answer": state.final_answer,
|
| 291 |
+
"steps_used": state.steps_used,
|
| 292 |
+
"started_at": state.started_at,
|
| 293 |
+
"finished_at": utc_now(),
|
| 294 |
+
"result_dir": str(state.result_dir),
|
| 295 |
+
"prompt_path": str(state.spec.prompt_path),
|
| 296 |
+
"env_builder_path": str(state.spec.env_builder_path),
|
| 297 |
+
"verifier_source_path": str(state.spec.verifier_path) if state.spec.verifier_path else None,
|
| 298 |
+
"workspace_before": str(state.workspace_before),
|
| 299 |
+
"workspace_after": str(state.workspace_after),
|
| 300 |
+
"conversation_history": str(state.history_path),
|
| 301 |
+
"env_builder": state.env_result,
|
| 302 |
+
"verifier": state.verifier_result,
|
| 303 |
+
"model": args.model,
|
| 304 |
+
"tokenizer": args.tokenizer or args.model,
|
| 305 |
+
"max_steps": args.max_steps,
|
| 306 |
+
"agent_batch_size": args.agent_batch_size,
|
| 307 |
+
"allow_python_tool": args.allow_python_tool,
|
| 308 |
+
"tool_call_transport": "local_vllm_json_text",
|
| 309 |
+
}
|
| 310 |
+
state.metadata_path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 311 |
+
return {
|
| 312 |
+
"task_id": state.spec.task_id,
|
| 313 |
+
"status": state.status,
|
| 314 |
+
"result_dir": str(state.result_dir),
|
| 315 |
+
"error": state.error,
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def write_task_state_history(state: TaskRunState) -> None:
|
| 320 |
+
write_history(
|
| 321 |
+
state.history_path,
|
| 322 |
+
spec=state.spec,
|
| 323 |
+
status=state.status,
|
| 324 |
+
final_answer=state.final_answer,
|
| 325 |
+
error=state.error,
|
| 326 |
+
messages=state.messages,
|
| 327 |
+
events=state.events,
|
| 328 |
+
started_at=state.started_at,
|
| 329 |
+
steps_used=state.steps_used,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def is_completed_result(result_dir: Path) -> bool:
|
| 334 |
+
metadata_path = result_dir / "runner_metadata.json"
|
| 335 |
+
if not metadata_path.is_file():
|
| 336 |
+
return False
|
| 337 |
+
try:
|
| 338 |
+
payload = json.loads(metadata_path.read_text(encoding="utf-8"))
|
| 339 |
+
except json.JSONDecodeError:
|
| 340 |
+
return False
|
| 341 |
+
return payload.get("status") == "completed"
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def run_env_builder(env_builder_path: Path, workspace: Path) -> dict[str, Any]:
|
| 345 |
+
started = time.time()
|
| 346 |
+
process = subprocess.run(
|
| 347 |
+
[sys.executable, str(env_builder_path)],
|
| 348 |
+
cwd=workspace,
|
| 349 |
+
text=True,
|
| 350 |
+
capture_output=True,
|
| 351 |
+
env=workspace_subprocess_env(workspace),
|
| 352 |
+
check=False,
|
| 353 |
+
)
|
| 354 |
+
result = {
|
| 355 |
+
"returncode": process.returncode,
|
| 356 |
+
"stdout": process.stdout,
|
| 357 |
+
"stderr": process.stderr,
|
| 358 |
+
"elapsed_seconds": round(time.time() - started, 3),
|
| 359 |
+
}
|
| 360 |
+
if process.returncode != 0:
|
| 361 |
+
raise RuntimeError(
|
| 362 |
+
f"env_builder.py failed for {env_builder_path} with code {process.returncode}\n"
|
| 363 |
+
f"stdout:\n{process.stdout}\n\nstderr:\n{process.stderr}"
|
| 364 |
+
)
|
| 365 |
+
return result
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def run_verifier(verifier_path: Path, workspace: Path, *, timeout: float) -> dict[str, Any]:
|
| 369 |
+
started = time.time()
|
| 370 |
+
try:
|
| 371 |
+
process = subprocess.run(
|
| 372 |
+
[sys.executable, str(verifier_path), str(workspace)],
|
| 373 |
+
cwd=verifier_path.parent,
|
| 374 |
+
text=True,
|
| 375 |
+
capture_output=True,
|
| 376 |
+
env=workspace_subprocess_env(workspace),
|
| 377 |
+
timeout=timeout,
|
| 378 |
+
check=False,
|
| 379 |
+
)
|
| 380 |
+
result: dict[str, Any] = {
|
| 381 |
+
"returncode": process.returncode,
|
| 382 |
+
"stdout": process.stdout,
|
| 383 |
+
"stderr": process.stderr,
|
| 384 |
+
"elapsed_seconds": round(time.time() - started, 3),
|
| 385 |
+
}
|
| 386 |
+
except subprocess.TimeoutExpired as exc:
|
| 387 |
+
result = {
|
| 388 |
+
"returncode": None,
|
| 389 |
+
"stdout": exc.stdout or "",
|
| 390 |
+
"stderr": exc.stderr or "",
|
| 391 |
+
"elapsed_seconds": round(time.time() - started, 3),
|
| 392 |
+
"error": f"verifier timed out after {timeout:g}s",
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
score_path = workspace / "workplace_score.json"
|
| 396 |
+
if score_path.is_file():
|
| 397 |
+
try:
|
| 398 |
+
result["workplace_score"] = json.loads(score_path.read_text(encoding="utf-8"))
|
| 399 |
+
except json.JSONDecodeError as exc:
|
| 400 |
+
result["workplace_score_error"] = str(exc)
|
| 401 |
+
return result
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def write_history(
|
| 405 |
+
path: Path,
|
| 406 |
+
*,
|
| 407 |
+
spec: TaskSpec,
|
| 408 |
+
status: str,
|
| 409 |
+
final_answer: str | None,
|
| 410 |
+
error: str | None,
|
| 411 |
+
messages: list[dict[str, str]],
|
| 412 |
+
events: list[dict[str, Any]],
|
| 413 |
+
started_at: str,
|
| 414 |
+
steps_used: int,
|
| 415 |
+
) -> None:
|
| 416 |
+
payload = {
|
| 417 |
+
"task_id": spec.task_id,
|
| 418 |
+
"status": status,
|
| 419 |
+
"final_answer": final_answer,
|
| 420 |
+
"error": error,
|
| 421 |
+
"started_at": started_at,
|
| 422 |
+
"updated_at": utc_now(),
|
| 423 |
+
"steps_used": steps_used,
|
| 424 |
+
"messages": messages,
|
| 425 |
+
"events": events,
|
| 426 |
+
}
|
| 427 |
+
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def write_summary(output_root: Path, results: list[dict[str, Any]], started_at: str) -> None:
|
| 431 |
+
summary = {
|
| 432 |
+
"started_at": started_at,
|
| 433 |
+
"finished_at": utc_now(),
|
| 434 |
+
"total": len(results),
|
| 435 |
+
"completed": sum(1 for result in results if result.get("status") == "completed"),
|
| 436 |
+
"failed": sum(1 for result in results if result.get("status") == "failed"),
|
| 437 |
+
"skipped": sum(1 for result in results if result.get("status") == "skipped"),
|
| 438 |
+
"results": results,
|
| 439 |
+
}
|
| 440 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 441 |
+
(output_root / "summary.json").write_text(
|
| 442 |
+
json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
|
| 443 |
+
encoding="utf-8",
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def iter_jsonl_results(results: Iterable[dict[str, Any]]) -> str:
|
| 448 |
+
return "".join(json.dumps(result, ensure_ascii=False) + "\n" for result in results)
|
vllm_nanoclaw_runtime/tasks.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from .types import TaskSpec
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def discover_tasks(base_tasks: Path, *, task_glob: str, task_ids: set[str] | None) -> list[TaskSpec]:
|
| 9 |
+
tasks_root = base_tasks / "tasks"
|
| 10 |
+
if not tasks_root.is_dir():
|
| 11 |
+
raise FileNotFoundError(f"tasks directory not found: {tasks_root}")
|
| 12 |
+
|
| 13 |
+
script_root = find_script_root(base_tasks)
|
| 14 |
+
specs: list[TaskSpec] = []
|
| 15 |
+
for task_dir in sorted(path for path in tasks_root.glob(task_glob) if path.is_dir()):
|
| 16 |
+
task_id = task_dir.name
|
| 17 |
+
if task_ids is not None and task_id not in task_ids:
|
| 18 |
+
continue
|
| 19 |
+
|
| 20 |
+
env_builder_path = task_dir / "env_builder.py"
|
| 21 |
+
if not env_builder_path.is_file():
|
| 22 |
+
continue
|
| 23 |
+
|
| 24 |
+
prompt_path = find_prompt_path(tasks_root, task_dir, task_id)
|
| 25 |
+
verifier_path = find_verifier_path(script_root, task_id) if script_root is not None else None
|
| 26 |
+
specs.append(
|
| 27 |
+
TaskSpec(
|
| 28 |
+
task_id=task_id,
|
| 29 |
+
task_dir=task_dir,
|
| 30 |
+
prompt_path=prompt_path,
|
| 31 |
+
env_builder_path=env_builder_path,
|
| 32 |
+
verifier_path=verifier_path,
|
| 33 |
+
)
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
if task_ids is not None:
|
| 37 |
+
found_ids = {spec.task_id for spec in specs}
|
| 38 |
+
missing_ids = sorted(task_ids - found_ids)
|
| 39 |
+
if missing_ids:
|
| 40 |
+
raise FileNotFoundError(f"requested task ids not found or missing env_builder.py: {missing_ids}")
|
| 41 |
+
if not specs:
|
| 42 |
+
raise FileNotFoundError(f"no task directories matched {task_glob!r} under {tasks_root}")
|
| 43 |
+
return specs
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def find_script_root(base_tasks: Path) -> Path | None:
|
| 47 |
+
for dirname in ("scrips", "scripts"):
|
| 48 |
+
candidate = base_tasks / dirname
|
| 49 |
+
if candidate.is_dir():
|
| 50 |
+
return candidate
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def find_prompt_path(tasks_root: Path, task_dir: Path, task_id: str) -> Path:
|
| 55 |
+
candidates = (
|
| 56 |
+
tasks_root / "prompts" / f"{task_id}.md",
|
| 57 |
+
task_dir / "prompt.md",
|
| 58 |
+
task_dir / "task.md",
|
| 59 |
+
)
|
| 60 |
+
for candidate in candidates:
|
| 61 |
+
if candidate.is_file():
|
| 62 |
+
return candidate
|
| 63 |
+
raise FileNotFoundError(
|
| 64 |
+
f"prompt file not found for {task_id}; tried: "
|
| 65 |
+
+ ", ".join(str(path) for path in candidates)
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def find_verifier_path(script_root: Path, task_id: str) -> Path | None:
|
| 70 |
+
candidates = (
|
| 71 |
+
script_root / task_id / "verify_workplace.py",
|
| 72 |
+
script_root / f"{task_id}.py",
|
| 73 |
+
script_root / "verify_workplace.py",
|
| 74 |
+
)
|
| 75 |
+
for candidate in candidates:
|
| 76 |
+
if candidate.is_file():
|
| 77 |
+
return candidate
|
| 78 |
+
return None
|
vllm_nanoclaw_runtime/tools.py
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import shlex
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
from .types import ToolResult
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
DANGEROUS_PYTHON_PATTERNS = (
|
| 16 |
+
"rm -",
|
| 17 |
+
"rmtree",
|
| 18 |
+
"unlink",
|
| 19 |
+
"remove(",
|
| 20 |
+
"removedirs",
|
| 21 |
+
"rmdir",
|
| 22 |
+
"os.system",
|
| 23 |
+
"os.popen",
|
| 24 |
+
"subprocess",
|
| 25 |
+
"shutil",
|
| 26 |
+
"send2trash",
|
| 27 |
+
"__import__",
|
| 28 |
+
"eval(",
|
| 29 |
+
"exec(",
|
| 30 |
+
"compile(",
|
| 31 |
+
"socket",
|
| 32 |
+
"httpx",
|
| 33 |
+
"requests",
|
| 34 |
+
"urllib",
|
| 35 |
+
)
|
| 36 |
+
ABSOLUTE_PATH_LITERAL = re.compile(r"[\"']/(?:[^\"']*)[\"']")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def execute_actions(
|
| 40 |
+
actions: list[dict[str, Any]],
|
| 41 |
+
workspace: Path,
|
| 42 |
+
*,
|
| 43 |
+
args: Any,
|
| 44 |
+
step: int,
|
| 45 |
+
) -> tuple[list[dict[str, Any]], str, bool, str | None]:
|
| 46 |
+
action_events: list[dict[str, Any]] = []
|
| 47 |
+
observations: list[str] = []
|
| 48 |
+
final_answer: str | None = None
|
| 49 |
+
is_final = False
|
| 50 |
+
|
| 51 |
+
for index, action in enumerate(actions, start=1):
|
| 52 |
+
result = execute_action(action, workspace, args=args, step=step)
|
| 53 |
+
action_name = str(action.get("action") or action.get("tool") or "<missing>")
|
| 54 |
+
action_events.append(
|
| 55 |
+
{
|
| 56 |
+
"index": index,
|
| 57 |
+
"action": action,
|
| 58 |
+
"observation": result.observation,
|
| 59 |
+
"is_final": result.is_final,
|
| 60 |
+
}
|
| 61 |
+
)
|
| 62 |
+
observations.append(f"Tool result {index} ({action_name}):\n{result.observation}")
|
| 63 |
+
if result.is_final:
|
| 64 |
+
is_final = True
|
| 65 |
+
final_answer = result.final_answer
|
| 66 |
+
break
|
| 67 |
+
|
| 68 |
+
return action_events, "\n\n".join(observations), is_final, final_answer
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def execute_action(action: dict[str, Any], workspace: Path, *, args: Any, step: int) -> ToolResult:
|
| 72 |
+
action_name = str(action.get("action", "")).strip()
|
| 73 |
+
try:
|
| 74 |
+
if action_name in {"list_dir", "ls"}:
|
| 75 |
+
path = str(action.get("path") or ".")
|
| 76 |
+
if bool(action.get("recursive", False)):
|
| 77 |
+
return ToolResult(list_dir_recursive(workspace, path, limit=args.list_limit))
|
| 78 |
+
return ToolResult(list_dir(workspace, path, limit=args.list_limit))
|
| 79 |
+
if action_name in {"read_file", "read"}:
|
| 80 |
+
return ToolResult(read_file(workspace, require_path_like(action), limit=args.read_limit))
|
| 81 |
+
if action_name in {"write_file", "write"}:
|
| 82 |
+
return ToolResult(write_file(workspace, require_path_like(action), require_string(action, "content")))
|
| 83 |
+
if action_name in {"edit_file", "edit"}:
|
| 84 |
+
return ToolResult(
|
| 85 |
+
edit_file(
|
| 86 |
+
workspace,
|
| 87 |
+
require_path_like(action),
|
| 88 |
+
require_string(action, "old_text"),
|
| 89 |
+
require_string(action, "new_text"),
|
| 90 |
+
replace_all=bool(action.get("replace_all", False)),
|
| 91 |
+
)
|
| 92 |
+
)
|
| 93 |
+
if action_name == "apply_patch":
|
| 94 |
+
changes = action.get("changes")
|
| 95 |
+
if not isinstance(changes, list):
|
| 96 |
+
return ToolResult("Error: 'changes' must be a list.")
|
| 97 |
+
return ToolResult(apply_workspace_patch(workspace, changes))
|
| 98 |
+
if action_name == "grep":
|
| 99 |
+
return ToolResult(
|
| 100 |
+
grep_workspace(
|
| 101 |
+
workspace,
|
| 102 |
+
require_string(action, "pattern"),
|
| 103 |
+
action.get("glob"),
|
| 104 |
+
limit=args.list_limit,
|
| 105 |
+
)
|
| 106 |
+
)
|
| 107 |
+
if action_name == "find":
|
| 108 |
+
return ToolResult(find_workspace_files(workspace, action.get("pattern"), limit=args.list_limit))
|
| 109 |
+
if action_name in {"memory_search", "memory_get", "memory_append"}:
|
| 110 |
+
return ToolResult("Error: memory is disabled in this local no-memory runner.")
|
| 111 |
+
if action_name in {"exec", "execute_dangerous_command"}:
|
| 112 |
+
return ToolResult(execute_workspace_command(workspace, str(action.get("command", ""))))
|
| 113 |
+
if action_name == "ask_human_for_confirmation":
|
| 114 |
+
command = str(action.get("command", ""))
|
| 115 |
+
return ToolResult(f"Human response: Reject (auto). Command not approved: {command}")
|
| 116 |
+
if action_name == "mkdir":
|
| 117 |
+
return ToolResult(make_dir(workspace, require_string(action, "path")))
|
| 118 |
+
if action_name == "run_python":
|
| 119 |
+
if not args.allow_python_tool:
|
| 120 |
+
return ToolResult("Error: run_python is disabled. Use read/write/edit/apply_patch actions instead.")
|
| 121 |
+
return ToolResult(run_python(workspace, require_string(action, "code"), step=step, timeout=args.python_timeout))
|
| 122 |
+
if action_name == "finish":
|
| 123 |
+
return ToolResult(
|
| 124 |
+
observation="Finished.",
|
| 125 |
+
is_final=True,
|
| 126 |
+
final_answer=str(action.get("answer") or ""),
|
| 127 |
+
)
|
| 128 |
+
if not action_name:
|
| 129 |
+
return ToolResult("Error: missing action field.")
|
| 130 |
+
return ToolResult(f"Error: Unknown tool '{action_name}'.")
|
| 131 |
+
except Exception as exc:
|
| 132 |
+
return ToolResult(f"Error while executing {action_name or '<missing>'}: {type(exc).__name__}: {exc}")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def require_string(action: dict[str, Any], key: str) -> str:
|
| 136 |
+
value = action.get(key)
|
| 137 |
+
if not isinstance(value, str):
|
| 138 |
+
raise ValueError(f"field {key!r} must be a string")
|
| 139 |
+
return value
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def require_path_like(action: dict[str, Any]) -> str:
|
| 143 |
+
value = action.get("path", action.get("filename"))
|
| 144 |
+
if not isinstance(value, str):
|
| 145 |
+
raise ValueError("field 'path' must be a string")
|
| 146 |
+
return value
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def resolve_workspace_path(workspace: Path, relative_path: str) -> Path:
|
| 150 |
+
raw_path = relative_path.strip() or "."
|
| 151 |
+
candidate_path = Path(raw_path)
|
| 152 |
+
if candidate_path.is_absolute():
|
| 153 |
+
raise ValueError(f"absolute paths are not allowed: {relative_path}")
|
| 154 |
+
if any(part == ".." for part in candidate_path.parts):
|
| 155 |
+
raise ValueError(f"parent path '..' is not allowed: {relative_path}")
|
| 156 |
+
resolved = (workspace / candidate_path).resolve()
|
| 157 |
+
workspace_resolved = workspace.resolve()
|
| 158 |
+
if resolved != workspace_resolved and workspace_resolved not in resolved.parents:
|
| 159 |
+
raise ValueError(f"path escapes workspace: {relative_path}")
|
| 160 |
+
return resolved
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def relative_workspace_path(workspace: Path, path: Path) -> str:
|
| 164 |
+
workspace_resolved = workspace.resolve()
|
| 165 |
+
path_resolved = path.resolve()
|
| 166 |
+
if path_resolved == workspace_resolved:
|
| 167 |
+
return "."
|
| 168 |
+
return path_resolved.relative_to(workspace_resolved).as_posix()
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def json_dumps(payload: Any) -> str:
|
| 172 |
+
return json.dumps(payload, ensure_ascii=False, indent=2)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def list_dir(workspace: Path, relative_path: str, *, limit: int) -> str:
|
| 176 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 177 |
+
if not path.exists():
|
| 178 |
+
return "Error: path not found."
|
| 179 |
+
if path.is_file():
|
| 180 |
+
return json_dumps(
|
| 181 |
+
{
|
| 182 |
+
"path": relative_workspace_path(workspace, path),
|
| 183 |
+
"entries": [
|
| 184 |
+
{
|
| 185 |
+
"path": relative_workspace_path(workspace, path),
|
| 186 |
+
"type": "file",
|
| 187 |
+
}
|
| 188 |
+
],
|
| 189 |
+
"truncated": False,
|
| 190 |
+
}
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
entries = []
|
| 194 |
+
truncated = False
|
| 195 |
+
for index, child in enumerate(sorted(path.iterdir())):
|
| 196 |
+
if index >= limit:
|
| 197 |
+
truncated = True
|
| 198 |
+
break
|
| 199 |
+
entries.append(
|
| 200 |
+
{
|
| 201 |
+
"path": relative_workspace_path(workspace, child),
|
| 202 |
+
"type": "dir" if child.is_dir() else "file",
|
| 203 |
+
}
|
| 204 |
+
)
|
| 205 |
+
return json_dumps(
|
| 206 |
+
{
|
| 207 |
+
"path": relative_workspace_path(workspace, path),
|
| 208 |
+
"entries": entries,
|
| 209 |
+
"truncated": truncated,
|
| 210 |
+
}
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def list_dir_recursive(workspace: Path, relative_path: str, *, limit: int) -> str:
|
| 215 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 216 |
+
if not path.exists():
|
| 217 |
+
return "Error: path not found."
|
| 218 |
+
if path.is_file():
|
| 219 |
+
return list_dir(workspace, relative_path, limit=limit)
|
| 220 |
+
|
| 221 |
+
entries = []
|
| 222 |
+
truncated = False
|
| 223 |
+
for index, child in enumerate(sorted(path.rglob("*"))):
|
| 224 |
+
if index >= limit:
|
| 225 |
+
truncated = True
|
| 226 |
+
break
|
| 227 |
+
entries.append(
|
| 228 |
+
{
|
| 229 |
+
"path": relative_workspace_path(workspace, child),
|
| 230 |
+
"type": "dir" if child.is_dir() else "file",
|
| 231 |
+
}
|
| 232 |
+
)
|
| 233 |
+
return json_dumps(
|
| 234 |
+
{
|
| 235 |
+
"path": relative_workspace_path(workspace, path),
|
| 236 |
+
"entries": entries,
|
| 237 |
+
"truncated": truncated,
|
| 238 |
+
}
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def read_file(workspace: Path, relative_path: str, *, limit: int) -> str:
|
| 243 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 244 |
+
if not path.exists():
|
| 245 |
+
return f"Error: file does not exist: {relative_path}"
|
| 246 |
+
if not path.is_file():
|
| 247 |
+
return f"Error: path is not a file: {relative_path}"
|
| 248 |
+
content = path.read_text(encoding="utf-8", errors="replace")
|
| 249 |
+
if len(content) > limit:
|
| 250 |
+
return content[:limit] + f"\n... truncated after {limit} characters"
|
| 251 |
+
return content
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def write_file(workspace: Path, relative_path: str, content: str) -> str:
|
| 255 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 256 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 257 |
+
path.write_text(content, encoding="utf-8")
|
| 258 |
+
return "Success: File written."
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def edit_file(
|
| 262 |
+
workspace: Path,
|
| 263 |
+
relative_path: str,
|
| 264 |
+
old_text: str,
|
| 265 |
+
new_text: str,
|
| 266 |
+
*,
|
| 267 |
+
replace_all: bool,
|
| 268 |
+
) -> str:
|
| 269 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 270 |
+
content = path.read_text(encoding="utf-8")
|
| 271 |
+
occurrences = content.count(old_text)
|
| 272 |
+
if occurrences == 0:
|
| 273 |
+
return "Error: target text not found."
|
| 274 |
+
if not replace_all and occurrences != 1:
|
| 275 |
+
return "Error: target text matched multiple locations. Pass replace_all=true or provide more specific old_text."
|
| 276 |
+
updated = content.replace(old_text, new_text) if replace_all else content.replace(old_text, new_text, 1)
|
| 277 |
+
path.write_text(updated, encoding="utf-8")
|
| 278 |
+
changed = occurrences if replace_all else 1
|
| 279 |
+
return f"Success: Applied {changed} edit(s)."
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def make_dir(workspace: Path, relative_path: str) -> str:
|
| 283 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 284 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 285 |
+
return f"Success: directory exists: {relative_path}."
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def apply_workspace_patch(workspace: Path, changes: list[Any]) -> str:
|
| 289 |
+
if not changes:
|
| 290 |
+
return "Error: no changes provided."
|
| 291 |
+
results: list[str] = []
|
| 292 |
+
for index, change in enumerate(changes, start=1):
|
| 293 |
+
if not isinstance(change, dict):
|
| 294 |
+
return f"Error: change #{index} must be an object."
|
| 295 |
+
try:
|
| 296 |
+
result = edit_file(
|
| 297 |
+
workspace,
|
| 298 |
+
require_path_like(change),
|
| 299 |
+
require_string(change, "old_text"),
|
| 300 |
+
require_string(change, "new_text"),
|
| 301 |
+
replace_all=bool(change.get("replace_all", False)),
|
| 302 |
+
)
|
| 303 |
+
except Exception as exc:
|
| 304 |
+
return f"Error: {type(exc).__name__}: {exc} (change #{index})"
|
| 305 |
+
if result.startswith("Error:"):
|
| 306 |
+
return f"{result} (change #{index})"
|
| 307 |
+
results.append(f"change #{index}: {result}")
|
| 308 |
+
return "Success: Patch applied.\n" + "\n".join(results)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def validate_glob_pattern(raw_pattern: str) -> str | None:
|
| 312 |
+
glob_path = Path(raw_pattern)
|
| 313 |
+
if glob_path.is_absolute() or any(part == ".." for part in glob_path.parts):
|
| 314 |
+
return "glob must stay inside the workspace"
|
| 315 |
+
return None
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def find_workspace_files(workspace: Path, pattern: Any, *, limit: int) -> str:
|
| 319 |
+
raw_pattern = str(pattern or "**/*").strip() or "**/*"
|
| 320 |
+
validation_error = validate_glob_pattern(raw_pattern)
|
| 321 |
+
if validation_error is not None:
|
| 322 |
+
return f"Error: {validation_error}."
|
| 323 |
+
|
| 324 |
+
files = []
|
| 325 |
+
truncated = False
|
| 326 |
+
for index, path in enumerate(sorted(path for path in workspace.glob(raw_pattern) if path.is_file())):
|
| 327 |
+
if index >= limit:
|
| 328 |
+
truncated = True
|
| 329 |
+
break
|
| 330 |
+
files.append(relative_workspace_path(workspace, path))
|
| 331 |
+
return json_dumps({"files": files, "truncated": truncated})
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def grep_workspace(workspace: Path, pattern: str, glob_pattern: Any, *, limit: int) -> str:
|
| 335 |
+
try:
|
| 336 |
+
regex = re.compile(pattern)
|
| 337 |
+
except re.error as exc:
|
| 338 |
+
return f"Error: invalid regex: {exc}"
|
| 339 |
+
|
| 340 |
+
raw_glob = str(glob_pattern or "**/*").strip() or "**/*"
|
| 341 |
+
validation_error = validate_glob_pattern(raw_glob)
|
| 342 |
+
if validation_error is not None:
|
| 343 |
+
return f"Error: {validation_error}."
|
| 344 |
+
|
| 345 |
+
matches: list[dict[str, Any]] = []
|
| 346 |
+
truncated = False
|
| 347 |
+
for path in sorted(path for path in workspace.glob(raw_glob) if path.is_file()):
|
| 348 |
+
try:
|
| 349 |
+
text = path.read_text(encoding="utf-8", errors="replace")
|
| 350 |
+
except OSError:
|
| 351 |
+
continue
|
| 352 |
+
relative = relative_workspace_path(workspace, path)
|
| 353 |
+
for line_number, line in enumerate(text.splitlines(), start=1):
|
| 354 |
+
if not regex.search(line):
|
| 355 |
+
continue
|
| 356 |
+
if len(matches) >= limit:
|
| 357 |
+
truncated = True
|
| 358 |
+
return json_dumps({"matches": matches, "truncated": truncated})
|
| 359 |
+
matches.append({"path": relative, "line": line_number, "text": line})
|
| 360 |
+
return json_dumps({"matches": matches, "truncated": truncated})
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def execute_workspace_command(workspace: Path, command: str) -> str:
|
| 364 |
+
raw = command.strip()
|
| 365 |
+
if not raw:
|
| 366 |
+
return "Error: Empty command"
|
| 367 |
+
try:
|
| 368 |
+
argv = shlex.split(raw)
|
| 369 |
+
except ValueError as exc:
|
| 370 |
+
return f"Error: Invalid command syntax: {exc}"
|
| 371 |
+
if not argv:
|
| 372 |
+
return "Error: Empty command"
|
| 373 |
+
|
| 374 |
+
name = argv[0]
|
| 375 |
+
if name == "pwd" and len(argv) == 1:
|
| 376 |
+
return str(workspace.resolve())
|
| 377 |
+
if name == "ls":
|
| 378 |
+
target = "."
|
| 379 |
+
recursive = False
|
| 380 |
+
for argument in argv[1:]:
|
| 381 |
+
if argument in {"-R", "--recursive"}:
|
| 382 |
+
recursive = True
|
| 383 |
+
continue
|
| 384 |
+
if argument.startswith("-"):
|
| 385 |
+
continue
|
| 386 |
+
target = argument
|
| 387 |
+
if recursive:
|
| 388 |
+
return list_dir_recursive(workspace, target, limit=500)
|
| 389 |
+
return list_dir(workspace, target, limit=500)
|
| 390 |
+
return "Error: Permission denied. Non-read-only exec commands are rejected by this local runner. Use read/write/edit/apply_patch tools instead."
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def run_python(workspace: Path, code: str, *, step: int, timeout: float) -> str:
|
| 394 |
+
safety_error = validate_python_tool_code(code)
|
| 395 |
+
if safety_error is not None:
|
| 396 |
+
return f"Error: blocked unsafe Python code: {safety_error}"
|
| 397 |
+
|
| 398 |
+
script_path = workspace / f".vllm_nanoclaw_step_{step}.py"
|
| 399 |
+
script_path.write_text(code, encoding="utf-8")
|
| 400 |
+
try:
|
| 401 |
+
try:
|
| 402 |
+
process = subprocess.run(
|
| 403 |
+
[sys.executable, str(script_path.name)],
|
| 404 |
+
cwd=workspace,
|
| 405 |
+
text=True,
|
| 406 |
+
capture_output=True,
|
| 407 |
+
env=workspace_subprocess_env(workspace),
|
| 408 |
+
timeout=timeout,
|
| 409 |
+
check=False,
|
| 410 |
+
)
|
| 411 |
+
except subprocess.TimeoutExpired as exc:
|
| 412 |
+
stdout = exc.stdout or ""
|
| 413 |
+
stderr = exc.stderr or ""
|
| 414 |
+
output_parts = []
|
| 415 |
+
if stdout:
|
| 416 |
+
output_parts.append(str(stdout).strip())
|
| 417 |
+
if stderr:
|
| 418 |
+
output_parts.append(f"[stderr]\n{str(stderr).strip()}")
|
| 419 |
+
output = "\n\n".join(output_parts) if output_parts else "(no output)"
|
| 420 |
+
return f"Error: Python timed out after {timeout:g}s\n{output}"
|
| 421 |
+
finally:
|
| 422 |
+
try:
|
| 423 |
+
script_path.unlink()
|
| 424 |
+
except FileNotFoundError:
|
| 425 |
+
pass
|
| 426 |
+
|
| 427 |
+
output_parts = []
|
| 428 |
+
if process.stdout.strip():
|
| 429 |
+
output_parts.append(process.stdout.strip())
|
| 430 |
+
if process.stderr.strip():
|
| 431 |
+
output_parts.append(f"[stderr]\n{process.stderr.strip()}")
|
| 432 |
+
output = "\n\n".join(output_parts) if output_parts else "(no output)"
|
| 433 |
+
if process.returncode != 0:
|
| 434 |
+
return f"Error: Python exited with code {process.returncode}\n{output}"
|
| 435 |
+
return output
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def validate_python_tool_code(code: str) -> str | None:
|
| 439 |
+
lowered = code.lower()
|
| 440 |
+
if ".." in code:
|
| 441 |
+
return "parent-directory path '..' is not allowed"
|
| 442 |
+
absolute_match = ABSOLUTE_PATH_LITERAL.search(code)
|
| 443 |
+
if absolute_match:
|
| 444 |
+
return f"absolute path literal is not allowed: {absolute_match.group(0)}"
|
| 445 |
+
for pattern in DANGEROUS_PYTHON_PATTERNS:
|
| 446 |
+
if pattern in lowered:
|
| 447 |
+
return f"forbidden pattern {pattern!r}"
|
| 448 |
+
return None
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def workspace_subprocess_env(workspace: Path) -> dict[str, str]:
|
| 452 |
+
workspace_resolved = workspace.resolve()
|
| 453 |
+
home_dir = workspace_resolved / ".runner_home"
|
| 454 |
+
tmp_dir = workspace_resolved / ".runner_tmp"
|
| 455 |
+
home_dir.mkdir(parents=True, exist_ok=True)
|
| 456 |
+
tmp_dir.mkdir(parents=True, exist_ok=True)
|
| 457 |
+
|
| 458 |
+
env = dict(os.environ)
|
| 459 |
+
env["HOME"] = str(home_dir)
|
| 460 |
+
env["TMPDIR"] = str(tmp_dir)
|
| 461 |
+
env["TEMP"] = str(tmp_dir)
|
| 462 |
+
env["TMP"] = str(tmp_dir)
|
| 463 |
+
env["PWD"] = str(workspace_resolved)
|
| 464 |
+
env["PYTHONNOUSERSITE"] = "1"
|
| 465 |
+
env["NANOCLAW_WORKSPACE"] = str(workspace_resolved)
|
| 466 |
+
return env
|
vllm_nanoclaw_runtime/types.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass(frozen=True, slots=True)
|
| 9 |
+
class TaskSpec:
|
| 10 |
+
task_id: str
|
| 11 |
+
task_dir: Path
|
| 12 |
+
prompt_path: Path
|
| 13 |
+
env_builder_path: Path
|
| 14 |
+
verifier_path: Path | None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass(frozen=True, slots=True)
|
| 18 |
+
class ToolResult:
|
| 19 |
+
observation: str
|
| 20 |
+
is_final: bool = False
|
| 21 |
+
final_answer: str | None = None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass(slots=True)
|
| 25 |
+
class TaskRunState:
|
| 26 |
+
spec: TaskSpec
|
| 27 |
+
result_dir: Path
|
| 28 |
+
workspace_before: Path
|
| 29 |
+
workspace_after: Path
|
| 30 |
+
history_path: Path
|
| 31 |
+
metadata_path: Path
|
| 32 |
+
prompt_text: str
|
| 33 |
+
env_result: dict[str, Any]
|
| 34 |
+
started_at: str
|
| 35 |
+
messages: list[dict[str, str]] = field(default_factory=list)
|
| 36 |
+
events: list[dict[str, Any]] = field(default_factory=list)
|
| 37 |
+
status: str = "running"
|
| 38 |
+
error: str | None = None
|
| 39 |
+
final_answer: str | None = None
|
| 40 |
+
steps_used: int = 0
|
| 41 |
+
verifier_result: dict[str, Any] | None = None
|