File size: 5,150 Bytes
93be2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
from __future__ import annotations

import json
import os
import signal
import subprocess
from typing import Any, Dict

import requests

from .registry import ToolRegistry


VLLM_BASE_URL = os.getenv("VLLM_BASE_URL", "http://localhost:8000/v1")


def t_serve_status(_: Dict[str, Any]) -> str:
    try:
        r = requests.get(f"{VLLM_BASE_URL.rstrip('/')}/health", timeout=5)
        return json.dumps({"status": r.status_code, "body": r.text})
    except Exception as e:
        return json.dumps({"error": str(e)})


def t_vllm_reload(args: Dict[str, Any]) -> str:
    """Attempt to restart the vLLM server via optional script or PID.
    Args: script (path) OR pid (int)
    """
    script = args.get("script")
    pid = args.get("pid")
    if script:
        try:
            proc = subprocess.run(["bash", script], capture_output=True, text=True, timeout=180)
            return json.dumps({"returncode": proc.returncode, "stdout": proc.stdout, "stderr": proc.stderr})
        except Exception as e:
            return json.dumps({"error": str(e)})
    if pid:
        try:
            os.kill(int(pid), signal.SIGHUP)
            return json.dumps({"status": "signaled", "pid": int(pid)})
        except Exception as e:
            return json.dumps({"error": str(e)})
    return json.dumps({"error": "script or pid required"})


def t_hf_pull_model(args: Dict[str, Any]) -> str:
    """Pull/refresh a HF repo into MODEL_PATH using hf CLI.
    Args: repo (org/name), dest (MODEL_PATH)
    """
    repo = args.get("repo")
    dest = args.get("dest") or os.getenv("MODEL_PATH", "/data/adaptai/platform/aiml/checkpoints/qwen3-8b-elizabeth-sft")
    token = os.getenv("HF_TOKEN") or os.getenv("HUGGING_FACE_API_KEY")
    if not repo:
        return json.dumps({"error": "repo required"})
    if not token:
        return json.dumps({"error": "HF_TOKEN not set"})
    try:
        proc = subprocess.run([
            "hf", "download", str(repo), "--repo-type", "model", "--include", "**", "--local-dir", str(dest)
        ], capture_output=True, text=True, timeout=3600)
        return json.dumps({"returncode": proc.returncode, "stdout": proc.stdout[-4000:], "stderr": proc.stderr[-4000:], "dest": dest})
    except Exception as e:
        return json.dumps({"error": str(e)})


def t_promote_checkpoint(args: Dict[str, Any]) -> str:
    """Promote a trained checkpoint to MODEL_PATH (rsync copy).
    Args: src (path), dest (optional overrides MODEL_PATH)
    """
    src = args.get("src")
    dest = args.get("dest") or os.getenv("MODEL_PATH", "/data/adaptai/platform/aiml/checkpoints/qwen3-8b-elizabeth-sft")
    if not src:
        return json.dumps({"error": "src required"})
    try:
        proc = subprocess.run(["rsync", "-aH", f"{src}/", f"{dest}/"], capture_output=True, text=True, timeout=3600)
        return json.dumps({"returncode": proc.returncode, "stdout": proc.stdout[-4000:], "stderr": proc.stderr[-4000:], "dest": dest})
    except Exception as e:
        return json.dumps({"error": str(e)})


def t_self_train(args: Dict[str, Any]) -> str:
    """Launch a training process (unconstrained). Provide 'script' and 'args' list.
    Example: {"script": "./train_elizabeth.sh", "args": ["--lr", "2e-5"]}
    """
    script = args.get("script")
    sargs = args.get("args") or []
    if not script:
        return json.dumps({"error": "script required"})
    try:
        cmd = ["bash", script] + list(map(str, sargs))
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        return json.dumps({"status": "started", "pid": proc.pid, "cmd": cmd})
    except Exception as e:
        return json.dumps({"error": str(e)})


def register_tools(reg: ToolRegistry) -> None:
    reg.register(
        name="serve_status",
        description="Check vLLM /health upstream.",
        parameters={"type": "object", "properties": {}},
        handler=t_serve_status,
    )
    reg.register(
        name="vllm_reload",
        description="Reload/restart vLLM via script or send SIGHUP to a PID.",
        parameters={"type": "object", "properties": {"script": {"type": "string"}, "pid": {"type": "integer"}}},
        handler=t_vllm_reload,
    )
    reg.register(
        name="hf_pull_model",
        description="Pull/refresh a Hugging Face model into MODEL_PATH.",
        parameters={"type": "object", "properties": {"repo": {"type": "string"}, "dest": {"type": "string"}}, "required": ["repo"]},
        handler=t_hf_pull_model,
    )
    reg.register(
        name="promote_checkpoint",
        description="Promote a trained checkpoint into serving MODEL_PATH using rsync.",
        parameters={"type": "object", "properties": {"src": {"type": "string"}, "dest": {"type": "string"}}, "required": ["src"]},
        handler=t_promote_checkpoint,
    )
    reg.register(
        name="self_train",
        description="Launch an unconstrained training job via provided script and args.",
        parameters={"type": "object", "properties": {"script": {"type": "string"}, "args": {"type": "array", "items": {"type": "string"}}}, "required": ["script"]},
        handler=t_self_train,
    )