glm53-flash-function-calling / generate_function_calling.py
Surfdan's picture
Add GLM-5.3-Flash synthetic function-calling generator
459df89 verified
Raw
History Blame Contribute Delete
16.7 kB
#!/usr/bin/env python3
"""
Synthetic function-calling dataset generator, powered by zai-org/GLM-5.3-Flash
through the Hugging Face Inference Providers OpenAI-compatible endpoint.
Pipeline — three model calls per example:
1. Scenario: the model invents a plausible scenario: 3-6 JSON-schema function
definitions, a user request, and whether tools are needed.
2. Call: the model answers the request with the tools attached
(tool_choice="required" for tool-using examples, "auto" for
negatives), producing real OpenAI-style tool_calls.
3. Simulate: the model fabricates plausible JSON results for each call, and a
final assistant turn answers with those results in context.
Every example is validated (arguments parse, match the schema, required keys
present) and deduplicated; invalid examples are dropped. Output is JSONL with
OpenAI `messages` + `tools` columns, and optionally the xlam single-turn format
in a second file.
Usage:
export HF_TOKEN=hf_...
python generate_function_calling.py --size 2000 --format both \
--out data/messages.jsonl --push-repo Surfdan/glm53-flash-function-calling
"""
import argparse
import json
import os
import random
import re
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from openai import OpenAI
MODEL = "zai-org/GLM-5.3-Flash"
BASE_URL = "https://router.huggingface.co/v1"
SYSTEM_WITH_TOOLS = (
"You are a helpful assistant with access to the tools provided. "
"Use them whenever they help answer the user's request, and give a direct "
"answer without tools when they are not needed."
)
DOMAINS = {
"weather": ["weather forecasts", "severe alerts", "historical climate data", "air quality"],
"travel": ["flight search", "hotel booking", "car rental", "itinerary planning"],
"finance": ["stock quotes", "currency conversion", "loan calculators", "budget tracking"],
"ecommerce": ["product search", "order tracking", "price alerts", "returns and refunds"],
"calendar": ["scheduling", "reminders", "meeting-room booking", "time zones"],
"devops": ["server monitoring", "deployments", "log search", "incident paging"],
"crm": ["contact lookup", "deal stages", "email logging", "lead scoring"],
"smarthome": ["lighting", "thermostats", "security cameras", "kitchen appliances"],
"media": ["movie lookup", "playlists", "podcast search", "subtitle handling"],
"food": ["recipe search", "restaurant reservations", "nutrition tracking", "grocery lists"],
"fitness": ["workout logs", "step counts", "heart-rate data", "race training plans"],
"realestate": ["listing search", "mortgage estimates", "comparable sales", "open houses"],
"logistics": ["shipment tracking", "fleet routing", "warehouse inventory", "customs documents"],
"education": ["course catalogs", "quiz generation", "grade books", "study plans"],
"hr": ["leave requests", "payroll", "org charts", "candidate pipelines"],
"productivity": ["notes", "todo lists", "document search", "file conversion"],
}
# Example-type mix: negatives teach the model NOT to call tools.
TYPE_WEIGHTS = {"tool": 0.85, "no_tool": 0.15}
_rate_lock = threading.Lock()
def chat(client, **kwargs):
"""Chat completion with exponential backoff. Returns the message or None."""
for attempt in range(6):
try:
resp = client.chat.completions.create(**kwargs)
return resp.choices[0].message
except Exception as e: # noqa: BLE001 - provider errors are heterogeneous
wait = min(60.0, 2.0 ** attempt * 1.5)
print(f"[warn] {type(e).__name__}: {e} — retry {attempt + 1} in {wait:.0f}s", flush=True)
time.sleep(wait)
return None
def extract_json(text):
"""Pull the first JSON object/array out of a model reply."""
if text is None:
return None
m = re.search(r"\{.*\}|\[.*\]", text, re.DOTALL)
if not m:
return None
for candidate in (m.group(0),):
try:
return json.loads(candidate)
except json.JSONDecodeError:
continue
return None
def valid_function(f):
if not isinstance(f, dict):
return False
name, params = f.get("name"), f.get("parameters")
return (
isinstance(name, str)
and re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_]{1,63}", name) is not None
and isinstance(params, dict)
and isinstance(params.get("properties"), dict)
and len(params["properties"]) > 0
)
def args_valid(func, args):
"""Check parsed arguments against the function's JSON schema (loose but useful)."""
if not isinstance(args, dict):
return False
props = func["parameters"].get("properties", {})
required = func["parameters"].get("required", [])
if not set(required).issubset(args):
return False
if not set(args).issubset(props):
return False
type_map = {"string": str, "number": (int, float), "integer": int,
"boolean": bool, "array": list, "object": dict}
for k, v in args.items():
t = props.get(k, {}).get("type")
if t == "number" and isinstance(v, bool):
return False
if t in type_map and not isinstance(v, type_map[t]):
return False
return True
def norm_tool_calls(message):
calls = []
for i, tc in enumerate(message.tool_calls or []):
calls.append({
"id": getattr(tc, "id", None) or f"call_{i}",
"type": "function",
"function": {"name": tc.function.name, "arguments": tc.function.arguments},
})
return calls
def build_example(client, rng, domain, hints, ex_type):
n_funcs = rng.randint(3, 6)
tool_rule = (
"The user's request must be answerable WITHOUT any of these functions "
"(the assistant should reply directly)."
if ex_type == "no_tool" else
"The user's request should naturally require calling at least one of the functions."
)
scen_prompt = f"""Design one realistic function-calling scenario in the domain "{domain}" (topics: {', '.join(hints)}).
Return ONLY a JSON object with these keys:
{{
"scenario": "one sentence describing the app/context where this assistant operates",
"functions": [{n_funcs} OpenAI-style function definitions, each with "name", "description", and "parameters" (a JSON Schema object with "type": "object", "properties", "required"). Give parameters realistic types and include optional ones sometimes.]
"user_query": "a natural user request that a real user would send. {tool_rule}"
}}
Requirements:
- Function names are snake_case and domain-appropriate. Vary parameter types (strings, numbers, enums, arrays, objects).
- The user query is 1-3 sentences, informal, with concrete details (names, dates, numbers). Never mention the function names.
- Be creative and specific; avoid generic templates."""
scen_msg = chat(client, model=MODEL, temperature=1.0, max_tokens=1600,
messages=[{"role": "user", "content": scen_prompt}])
scen = extract_json(scen_msg.content if scen_msg else None)
if not isinstance(scen, dict):
return None
funcs = [f for f in scen.get("functions", []) if valid_function(f)]
if len(funcs) < 3 or not scen.get("user_query"):
return None
query = str(scen["user_query"]).strip()
# --- Stage B: generate the assistant's tool calls -------------------------
stage_b_msgs = [{"role": "system", "content": SYSTEM_WITH_TOOLS},
{"role": "user", "content": query}]
resp = chat(client, model=MODEL, temperature=0.7, max_tokens=700,
messages=stage_b_msgs,
tools=funcs,
tool_choice="required" if ex_type == "tool" else "auto")
if resp is None:
return None
calls = norm_tool_calls(resp)
if ex_type == "no_tool":
if calls: # model called tools anyway — keep it as a tool example
ex_type = "tool"
else:
content = (resp.content or "").strip()
if len(content) < 10:
return None
return {"messages": [
{"role": "system", "content": SYSTEM_WITH_TOOLS},
{"role": "user", "content": query},
{"role": "assistant", "content": content}],
"tools": funcs, "type": "no_tool", "domain": domain}
# Validate and parse every call's arguments against its schema.
parsed = []
for tc in calls:
try:
args = json.loads(tc["function"]["arguments"])
except json.JSONDecodeError:
args = None
func = next((f for f in funcs if f["name"] == tc["function"]["name"]), None)
if func is None or not args_valid(func, args):
continue
parsed.append((tc, args))
if not parsed:
return None
# --- Stage C: simulate plausible tool results -----------------------------
call_desc = "\n".join(
f"{i + 1}. {tc['function']['name']}({json.dumps(args, ensure_ascii=False)})"
for i, (tc, args) in enumerate(parsed))
sim_prompt = f"""You are simulating the backends for these functions:
{json.dumps(funcs, indent=1)}
The assistant made these calls:
{call_desc}
Return ONLY a JSON array with one object per call, IN ORDER, that each function
would realistically return given its arguments. Match each function's implied
return shape. Include realistic values (IDs, timestamps, statuses), not placeholders."""
sim_msg = chat(client, model=MODEL, temperature=0.7, max_tokens=1200,
messages=[{"role": "user", "content": sim_prompt}])
results = extract_json(sim_msg.content if sim_msg else None)
if not isinstance(results, list) or len(results) != len(parsed):
return None
tool_msgs = [{"role": "tool", "tool_call_id": tc["id"], "name": tc["function"]["name"],
"content": json.dumps(res)} for (tc, _), res in zip(parsed, results)]
# --- Stage D: final assistant answer with results in context --------------
final_msgs = [{"role": "system", "content": SYSTEM_WITH_TOOLS},
{"role": "user", "content": query},
{"role": "assistant", "content": None, "tool_calls": [tc for tc, _ in parsed]},
*tool_msgs]
final = chat(client, model=MODEL, temperature=0.7, max_tokens=500, messages=final_msgs)
if final is None or not (final.content or "").strip():
return None
messages = [{"role": "system", "content": SYSTEM_WITH_TOOLS},
{"role": "user", "content": query},
{"role": "assistant", "content": None, "tool_calls": [tc for tc, _ in parsed]},
*tool_msgs,
{"role": "assistant", "content": final.content.strip()}]
return {"messages": messages, "tools": funcs, "type": "tool",
"n_calls": len(parsed), "domain": domain}
def worker(client, rng, out_files, lock, state, args):
while state["success"] < args.size:
if state["success"] + state["pending"] >= args.size + 200:
return # enough in flight
with state["lock"]:
state["pending"] += 1
domain = rng.choice(list(DOMAINS))
ex_type = rng.choices(list(TYPE_WEIGHTS), weights=list(TYPE_WEIGHTS.values()))[0]
rec = build_example(client, rng, domain, DOMAINS[domain], ex_type)
with state["lock"]:
state["pending"] -= 1
if rec is None:
state["fail"] += 1
continue
qhash = hash(rec["messages"][1]["content"])
if qhash in state["seen"]:
state["fail"] += 1
continue
state["seen"].add(qhash)
rec["id"] = f"{args.seed_id}-{state['success'] + 1:06d}"
for fmt in args._formats:
row = to_row(rec, fmt)
out_files[fmt].write(json.dumps(row, ensure_ascii=False) + "\n")
out_files[fmt].flush()
state["success"] += 1
if state["success"] % 25 == 0:
print(f"[progress] {state['success']}/{args.size} "
f"(fail={state['fail']})", flush=True)
if args.trackio:
log_progress(args, state)
def to_row(rec, fmt):
if fmt == "messages":
return {"id": rec["id"], "messages": rec["messages"], "tools": rec["tools"],
"domain": rec["domain"], "type": rec["type"]}
answers = []
if rec["type"] == "tool":
m = rec["messages"][2]
for tc in m["tool_calls"]:
answers.append({"name": tc["function"]["name"],
"arguments": json.loads(tc["function"]["arguments"])})
return {"id": rec["id"], "query": rec["messages"][1]["content"],
"tools": rec["tools"], "answers": answers}
def log_progress(args, state):
try:
import trackio
if not getattr(log_progress, "_init", False):
trackio.init(project="glm53-flash-function-calling",
space_id=os.environ.get("TRACKIO_SPACE_ID"))
log_progress._init = True
trackio.log({"examples": state["success"], "failures": state["fail"]},
step=state["success"])
except Exception as e: # noqa: BLE001 - metrics must never kill the run
print(f"[warn] trackio: {e}", flush=True)
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--size", type=int, default=2000, help="number of validated examples")
ap.add_argument("--out", default="data", help="output directory for JSONL files")
ap.add_argument("--format", choices=["messages", "xlam", "both"], default="messages")
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--provider", default=None, help="pin a provider, e.g. novita")
ap.add_argument("--push-repo", default=None, help="upload results to this dataset repo")
ap.add_argument("--seed-id", default="glm53fc")
args = ap.parse_args()
args.trackio = bool(os.environ.get("TRACKIO_SPACE_ID"))
os.makedirs(args.out, exist_ok=True)
formats = ["messages", "xlam"] if args.format == "both" else [args.format]
paths = {fmt: os.path.join(args.out, f"{fmt}.jsonl") for fmt in formats}
model = MODEL if args.provider is None else f"{MODEL}:{args.provider}"
token = os.environ.get("HF_TOKEN")
assert token, "HF_TOKEN must be set (a token with Inference Providers access)"
client = OpenAI(base_url=BASE_URL, api_key=token)
# Smoke-check: the model id must resolve before generating anything.
ping = chat(client, model=model, max_tokens=5,
messages=[{"role": "user", "content": "Say OK."}])
assert ping is not None, f"{model} did not respond through the router"
print(f"[ok] {model} reachable — starting generation", flush=True)
state = {"success": 0, "fail": 0, "pending": 0, "lock": threading.Lock(),
"seen": set(), "rng": random.Random(20260925)}
out_files = {}
for fmt, path in paths.items():
if os.path.exists(path): # resume: keep existing rows, restore dedup set
with open(path) as f:
for line in f:
try:
state["seen"].add(hash(json.loads(line)["query"]))
except Exception:
pass
print(f"[resume] {path} exists — appending after dedup against it", flush=True)
out_files[fmt] = open(path, "a", encoding="utf-8")
rng = random.Random(20260925)
with ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(worker, client, rng, out_files, None, state, args)
for _ in range(args.workers)]
for f in as_completed(futures):
f.result()
for f in out_files.values():
f.close()
print(f"[done] {state['success']} examples, {state['fail']} dropped", flush=True)
assert state["success"] >= args.size * 0.8, "yield was too low — inspect warnings above"
if args.push_repo:
from huggingface_hub import HfApi
api = HfApi(token=token)
for fmt, path in paths.items():
api.upload_file(path_or_fileobj=path, path_in_repo=f"data/{os.path.basename(path)}",
repo_id=args.push_repo, repo_type="dataset",
commit_message=f"Add {fmt} split ({state['success']} examples)")
print(f"[pushed] https://huggingface.co/datasets/{args.push_repo}", flush=True)
if __name__ == "__main__":
main()