File size: 6,468 Bytes
9b2f1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python3
"""SFT rows: chain commands, don't repeat ls, stop after the artifact exists."""
from __future__ import annotations

import json
import random
from pathlib import Path

from datasets import Dataset, load_dataset

SYS = """You are an expert coding assistant operating inside pi.
Be concise. Prefer one bash call that chains steps with && or newlines.
Never repeat the same ls/find/pwd. After the required output exists, say one short sentence and STOP. Do not celebrate via more commands."""

TOOLS = json.dumps(
    [
        {
            "type": "function",
            "function": {
                "name": "bash",
                "description": "Execute a bash command",
                "parameters": {
                    "type": "object",
                    "properties": {"command": {"type": "string"}},
                    "required": ["command"],
                },
            },
        },
        {
            "type": "function",
            "function": {
                "name": "write",
                "description": "Write a file",
                "parameters": {
                    "type": "object",
                    "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
                    "required": ["path", "content"],
                },
            },
        },
        {
            "type": "function",
            "function": {
                "name": "read",
                "description": "Read a file",
                "parameters": {
                    "type": "object",
                    "properties": {"path": {"type": "string"}},
                    "required": ["path"],
                },
            },
        },
        {
            "type": "function",
            "function": {
                "name": "edit",
                "description": "Edit a file",
                "parameters": {
                    "type": "object",
                    "properties": {"path": {"type": "string"}, "edits": {"type": "array"}},
                    "required": ["path", "edits"],
                },
            },
        },
    ]
)


def tc(i, name, args):
    return {"id": f"c{i}", "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}


def asst(text, calls=None):
    m = {"role": "assistant", "content": text}
    if calls:
        m["tool_calls"] = calls
    return m


def tool(i, content):
    return {"role": "tool", "tool_call_id": f"c{i}", "content": content}


def pack(msgs, src):
    return {"messages": [{"role": "system", "content": SYS}] + msgs, "tools": TOOLS, "source": src}


def main():
    rng = random.Random(11)
    rows = []

    for i in range(400):
        rows.append(
            pack(
                [
                    {"role": "user", "content": f"Write READY to /output/status{i}.txt then stop."},
                    asst(
                        "Writing the file.",
                        [tc(0, "bash", {"command": f"mkdir -p /output && printf 'READY\\n' > /output/status{i}.txt && cat /output/status{i}.txt"})],
                    ),
                    tool(0, "READY\n"),
                    asst("Wrote /output/status.txt."),
                ],
                "stop:write",
            )
        )

    for i in range(250):
        rows.append(
            pack(
                [
                    {"role": "user", "content": "Explore once, then compile src/main.c to /output/app and stop."},
                    asst(
                        "Listing and compiling in one command.",
                        [tc(0, "bash", {"command": "ls -la && gcc -O2 src/main.c -o /output/app && ls -la /output/app"})],
                    ),
                    tool(0, "-rwxr-xr-x 1 root root 16384 app\n"),
                    asst("Built /output/app."),
                ],
                "stop:build",
            )
        )

    for i in range(250):
        rows.append(
            pack(
                [
                    {"role": "user", "content": "Fix the off-by-one in add.py and run the test. Stop when it passes."},
                    asst("Reading, patching, testing.", [tc(0, "bash", {"command": "cat add.py && python3 - <<'PY'\nfrom pathlib import Path\np=Path('add.py')\np.write_text(p.read_text().replace('a + b + 1','a + b'))\nPY\npython3 -c 'from add import add; assert add(2,2)==4'"})]),
                    tool(0, ""),
                    asst("Fixed add.py; test passed."),
                ],
                "stop:fix",
            )
        )

    # saw listing already -> do not list again
    for i in range(200):
        rows.append(
            pack(
                [
                    {"role": "user", "content": "There is a bug in util.py. Find it and patch it."},
                    asst("Listing once.", [tc(0, "bash", {"command": "ls && cat util.py"})]),
                    tool(0, "README.md\nutil.py\ndef inc(x):\n    return x\n"),
                    asst(
                        "Patching without listing again.",
                        [
                            tc(
                                1,
                                "edit",
                                {"path": "util.py", "edits": [{"oldText": "    return x\n", "newText": "    return x + 1\n"}]},
                            )
                        ],
                    ),
                    tool(1, "Edited util.py"),
                    asst("inc now returns x+1."),
                ],
                "stop:no-relist",
            )
        )

    # mix prior finish data
    prev = Path("/var/lib/agentptb-cache/tb1/tmp/sft-data/pi-sft-finish/train.parquet")
    if prev.exists():
        ds = load_dataset("parquet", data_files=str(prev), split="train")
        idx = list(range(len(ds)))
        rng.shuffle(idx)
        for j in idx[:4000]:
            rec = ds[j]
            rows.append({"messages": rec["messages"], "tools": rec["tools"], "source": rec["source"]})

    rng.shuffle(rows)
    out = Path("/var/lib/agentptb-cache/tb1/tmp/sft-data/pi-sft-stop")
    out.mkdir(parents=True, exist_ok=True)
    Dataset.from_dict(
        {
            "messages": [r["messages"] for r in rows],
            "tools": [r["tools"] if isinstance(r["tools"], str) else json.dumps(r["tools"]) for r in rows],
            "source": [r["source"] for r in rows],
        }
    ).to_parquet(str(out / "train.parquet"))
    print("wrote", len(rows), out)


if __name__ == "__main__":
    main()