hermes-agentic-tool-sft / scripts /generate_corpus.py
vcruz305's picture
Upload scripts/generate_corpus.py with huggingface_hub
6ae0bbd verified
Raw
History Blame Contribute Delete
16.3 kB
#!/usr/bin/env python3
"""Build a public Hermes-agentic SFT corpus (synthetic, Apache-2.0).
Teaches models to call Hermes tools correctly and STOP — not to loop.
No third-party distill, no live home-directory traces.
"""
from __future__ import annotations
import hashlib
import json
import random
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data"
RNG = random.Random(20260813)
TOOLS = {
"terminal": {
"type": "function",
"function": {
"name": "terminal",
"description": "Execute a shell command. Do not repeat a command whose output you already have.",
"parameters": {
"type": "object",
"properties": {
"command": {"type": "string", "description": "The command to execute"},
"timeout": {"type": "integer", "minimum": 1},
"workdir": {"type": "string"},
},
"required": ["command"],
},
},
},
"read_file": {
"type": "function",
"function": {
"name": "read_file",
"description": "Read a text file.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string"},
"offset": {"type": "integer"},
"limit": {"type": "integer"},
},
"required": ["path"],
},
},
},
"search_files": {
"type": "function",
"function": {
"name": "search_files",
"description": "Search file contents or names.",
"parameters": {
"type": "object",
"properties": {
"pattern": {"type": "string"},
"path": {"type": "string"},
"target": {"type": "string", "enum": ["content", "files"]},
},
"required": ["pattern"],
},
},
},
"write_file": {
"type": "function",
"function": {
"name": "write_file",
"description": "Write a text file. Overwrites the entire file.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string"},
"content": {"type": "string"},
},
"required": ["path", "content"],
},
},
},
"web_search": {
"type": "function",
"function": {
"name": "web_search",
"description": "Search the public web. One good search is enough; do not retry an identical query.",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string"}, "limit": {"type": "integer"}},
"required": ["query"],
},
},
},
"web_extract": {
"type": "function",
"function": {
"name": "web_extract",
"description": "Fetch a URL as text. Not a search engine.",
"parameters": {
"type": "object",
"properties": {"urls": {"type": "array", "items": {"type": "string"}}},
"required": ["urls"],
},
},
},
"todo": {
"type": "function",
"function": {
"name": "todo",
"description": "Write or update an in-session task list.",
"parameters": {
"type": "object",
"properties": {
"todos": {"type": "array"},
"merge": {"type": "boolean"},
},
"required": ["todos"],
},
},
},
}
CORE = ["terminal", "read_file", "search_files", "write_file", "web_search"]
def tc(i: str, name: str, args: dict) -> dict:
return {
"id": i,
"type": "function",
"function": {"name": name, "arguments": json.dumps(args, separators=(",", ":"))},
}
def row(tag: str, messages: list, tool_names: list[str], extra: str = "") -> dict:
seq = next_seq()
blob = json.dumps({"tag": tag, "messages": messages, "x": extra, "n": seq}, sort_keys=True)
rid = hashlib.sha1(blob.encode()).hexdigest()[:12]
return {
"id": f"{tag}-{seq:04d}-{rid}",
"tag": tag,
"source": "synthetic-hermes-v1",
"license": "apache-2.0",
"messages": messages,
"tools": [TOOLS[n] for n in tool_names],
}
_SEQ = 0
def next_seq() -> int:
global _SEQ
_SEQ += 1
return _SEQ
PROJECTS = [
("demo", ["README.md", "src/app.py", "data/config.yaml"], "8084"),
("api", ["README.md", "app/main.py", "config/settings.toml"], "8000"),
("bot", ["README.md", "hermes_bot.py", "env.example"], "8083"),
("web", ["README.md", "frontend/index.html", "nginx.conf"], "443"),
("ml", ["README.md", "train.py", "configs/base.yaml"], "6006"),
("cli", ["README.md", "src/cli.py", "pyproject.toml"], "0"),
("gate", ["README.md", "hermes_loop_gate.py", "docs/serve.md"], "8084"),
("agent", ["README.md", "agent/loop.py", "prompts/system.md"], "11434"),
("svc", ["README.md", "service.py", "deploy/compose.yml"], "9090"),
("lib", ["README.md", "src/lib.rs", "Cargo.toml"], "0"),
]
QUERIES = [
("latest stable Python 3", "Python 3.14.6 is the latest stable release.", "3.14.6"),
("Hermes Agent tool calling", "Hermes Agent uses OpenAI-style tools= / tool_calls.", "OpenAI tool_calls"),
("Muse Glimmer context length", "Muse Glimmer documents a 131K context window.", "131K"),
("llama.cpp server OpenAI API", "llama-server exposes POST /v1/chat/completions.", "/v1/chat/completions"),
("current UTC date", "The cited page lists Thursday, 13 August 2026.", "13 August 2026"),
]
def stop_ls() -> dict:
name, files, _ = RNG.choice(PROJECTS)
listing = "\n".join(files) + "\n"
return row(
"stop",
[
{"role": "user", "content": f"List files in the {name} workspace. Then stop and name them. Do not list again."},
{"role": "assistant", "tool_calls": [tc("c1", "terminal", {"command": RNG.choice(["ls", "ls -la", "dir"])})]},
{"role": "tool", "tool_call_id": "c1", "content": listing},
{"role": "assistant", "content": "Files: " + ", ".join(files) + "."},
],
["terminal", "search_files", "read_file"],
name,
)
def stop_read() -> dict:
name, files, port = RNG.choice(PROJECTS)
path = files[-1]
return row(
"stop",
[
{"role": "user", "content": f"Read {path} and tell me the port. One read is enough."},
{"role": "assistant", "tool_calls": [tc("c1", "read_file", {"path": path})]},
{"role": "tool", "tool_call_id": "c1", "content": f"port = {port}\nhost = 127.0.0.1\n"},
{"role": "assistant", "content": f"The port is {port}."},
],
["read_file", "terminal"],
path,
)
def stop_search() -> dict:
name, files, port = RNG.choice(PROJECTS)
hit = files[-1]
return row(
"stop",
[
{"role": "user", "content": f"Find which file sets the listen port in {name}. Then stop."},
{"role": "assistant", "tool_calls": [tc("c1", "search_files", {"pattern": "port", "target": "content"})]},
{"role": "tool", "tool_call_id": "c1", "content": f"{hit}:1:port = {port}"},
{"role": "assistant", "content": f"{hit} sets port {port}."},
],
["search_files", "read_file"],
hit,
)
def stop_write() -> dict:
path = RNG.choice(["notes.txt", "out/ok.txt", "STATUS.md"])
word = RNG.choice(["ready", "ok", "done"])
return row(
"stop",
[
{"role": "user", "content": f"Write {path} containing just '{word}'. Then stop."},
{"role": "assistant", "tool_calls": [tc("c1", "write_file", {"path": path, "content": word + "\n"})]},
{"role": "tool", "tool_call_id": "c1", "content": f"wrote {path} ({len(word)+1} bytes)"},
{"role": "assistant", "content": f"Wrote {path}."},
],
["write_file", "terminal"],
path,
)
def stop_web() -> dict:
q, snippet, ans = RNG.choice(QUERIES)
return row(
"stop",
[
{"role": "user", "content": f"Search the web once for {q}. Then answer briefly. Do not extract extra URLs."},
{"role": "assistant", "tool_calls": [tc("c1", "web_search", {"query": q})]},
{"role": "tool", "tool_call_id": "c1", "content": f"1. {snippet} — https://example.test/a"},
{"role": "assistant", "content": ans},
],
["web_search", "web_extract"],
q,
)
def stop_todo() -> dict:
return row(
"stop",
[
{"role": "user", "content": "Plan a 3-step audit of this repo as a todo list. Do not start the audit."},
{
"role": "assistant",
"tool_calls": [
tc(
"c1",
"todo",
{
"todos": [
{"id": "1", "content": "List top-level files", "status": "pending"},
{"id": "2", "content": "Read the README", "status": "pending"},
{"id": "3", "content": "Note open questions", "status": "pending"},
]
},
)
],
},
{"role": "tool", "tool_call_id": "c1", "content": "ok, 3 todos"},
{"role": "assistant", "content": "Planned three steps: list files, read README, note questions. Not starting yet."},
],
["todo", "web_search", "terminal"],
"todo",
)
def no_tool_math() -> dict:
a, b = RNG.randint(11, 40), RNG.randint(11, 40)
return row(
"no_tool",
[
{"role": "user", "content": f"What is {a} times {b}? Reply with just the number. Do not use tools."},
{"role": "assistant", "content": str(a * b)},
],
CORE,
f"{a}x{b}",
)
def no_tool_def() -> dict:
q, a = RNG.choice(
[
("In one sentence, what is a JSON schema? Do not run shell commands.", "A JSON Schema is a JSON document that declares the shape, types, and constraints of other JSON data."),
("What is OpenAI tool calling? One sentence. No tools.", "The model emits structured tool_calls; the client runs the function and returns a tool message."),
("What does HIT_CAP mean in an agent bench? No tools.", "The model kept calling tools until the turn limit with no user-facing answer."),
]
)
return row("no_tool", [{"role": "user", "content": q}, {"role": "assistant", "content": a}], CORE, q[:40])
def recover_missing() -> dict:
name, files, port = RNG.choice(PROJECTS)
bad, good = "config.yaml", files[-1]
return row(
"recover",
[
{"role": "user", "content": f"Read {bad} and tell me the port."},
{"role": "assistant", "tool_calls": [tc("c1", "read_file", {"path": bad})]},
{"role": "tool", "tool_call_id": "c1", "content": f"ERROR: File not found: {bad}. Try {good}"},
{"role": "assistant", "tool_calls": [tc("c2", "read_file", {"path": good})]},
{"role": "tool", "tool_call_id": "c2", "content": f"port = {port}\n"},
{"role": "assistant", "content": f"{bad} is missing. {good} sets port {port}."},
],
["read_file", "search_files"],
good,
)
def recover_perm() -> dict:
cmd = RNG.choice(["cat /etc/secret.conf", "cat /root/.env"])
return row(
"recover",
[
{"role": "user", "content": f"Show me the contents using the terminal: {cmd}"},
{"role": "assistant", "tool_calls": [tc("c1", "terminal", {"command": cmd})]},
{"role": "tool", "tool_call_id": "c1", "content": "ERROR: permission denied"},
{"role": "assistant", "content": "That path is not readable here (permission denied). I will not keep retrying the same command."},
],
["terminal", "read_file"],
cmd,
)
def dead_web() -> dict:
q, _, _ = RNG.choice(QUERIES)
err = RNG.choice(
[
"ERROR: search backend unavailable (ddgs package is not installed).",
"ERROR: FIRECRAWL_API_KEY is not set; extract/search backend unavailable.",
"ERROR: DuckDuckGo (ddgs) is a search-only backend and cannot fetch arbitrary URLs.",
]
)
return row(
"dead_tool",
[
{"role": "user", "content": f"Search the web for {q}."},
{"role": "assistant", "tool_calls": [tc("c1", "web_search", {"query": q})]},
{"role": "tool", "tool_call_id": "c1", "content": err},
{
"role": "assistant",
"content": "Web search is not available on this instance. I will not retry the same call. Configure a search backend (for example ddgs) if you want me to look it up.",
},
],
["web_search", "web_extract"],
err[:40],
)
def dead_extract() -> dict:
return row(
"dead_tool",
[
{"role": "user", "content": "Search once for the latest stable Python 3, then answer. Do not fetch extra pages if extract fails."},
{"role": "assistant", "tool_calls": [tc("c1", "web_search", {"query": "Python 3 latest stable version"})]},
{"role": "tool", "tool_call_id": "c1", "content": "1. Python 3.14.6 is the latest stable release."},
{"role": "assistant", "content": "Latest stable is 3.14.6."},
],
["web_search", "web_extract"],
"no-extract",
)
def schema_fix() -> dict:
return row(
"schema",
[
{"role": "user", "content": "Run `pwd` using the terminal tool, then report the result."},
{"role": "assistant", "tool_calls": [tc("c1", "terminal", {"command": "pwd"})]},
{"role": "tool", "tool_call_id": "c1", "content": "/workspace/demo\n"},
{"role": "assistant", "content": "pwd → /workspace/demo"},
],
["terminal"],
"pwd",
)
def schema_not_code() -> dict:
return row(
"schema",
[
{"role": "user", "content": "Use the terminal to echo hello. Put the shell command in the command field, not a Python code field."},
{"role": "assistant", "tool_calls": [tc("c1", "terminal", {"command": "echo hello"})]},
{"role": "tool", "tool_call_id": "c1", "content": "hello\n"},
{"role": "assistant", "content": "hello"},
],
["terminal"],
"echo",
)
BUILDERS = [
(stop_ls, 280),
(stop_read, 260),
(stop_search, 180),
(stop_write, 140),
(stop_web, 180),
(stop_todo, 80),
(no_tool_math, 160),
(no_tool_def, 80),
(recover_missing, 160),
(recover_perm, 80),
(dead_web, 160),
(dead_extract, 80),
(schema_fix, 80),
(schema_not_code, 60),
]
def main() -> None:
rows = []
seen = set()
for fn, n in BUILDERS:
got = 0
spins = 0
while got < n and spins < n * 20:
spins += 1
r = fn()
if r["id"] in seen:
continue
seen.add(r["id"])
rows.append(r)
got += 1
RNG.shuffle(rows)
n_val = max(80, len(rows) // 10)
val = rows[:n_val]
train = rows[n_val:]
DATA.mkdir(parents=True, exist_ok=True)
for name, part in ("train.jsonl", train), ("validation.jsonl", val):
path = DATA / name
with path.open("w", encoding="utf-8") as f:
for r in part:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
tags = {}
for r in rows:
tags[r["tag"]] = tags.get(r["tag"], 0) + 1
print(json.dumps({"n": len(rows), "train": len(train), "validation": len(val), "tags": tags}, indent=2))
if __name__ == "__main__":
main()