Surfdan commited on
Commit
459df89
·
verified ·
1 Parent(s): fc1842f

Add GLM-5.3-Flash synthetic function-calling generator

Browse files
Files changed (1) hide show
  1. generate_function_calling.py +377 -0
generate_function_calling.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Synthetic function-calling dataset generator, powered by zai-org/GLM-5.3-Flash
4
+ through the Hugging Face Inference Providers OpenAI-compatible endpoint.
5
+
6
+ Pipeline — three model calls per example:
7
+ 1. Scenario: the model invents a plausible scenario: 3-6 JSON-schema function
8
+ definitions, a user request, and whether tools are needed.
9
+ 2. Call: the model answers the request with the tools attached
10
+ (tool_choice="required" for tool-using examples, "auto" for
11
+ negatives), producing real OpenAI-style tool_calls.
12
+ 3. Simulate: the model fabricates plausible JSON results for each call, and a
13
+ final assistant turn answers with those results in context.
14
+
15
+ Every example is validated (arguments parse, match the schema, required keys
16
+ present) and deduplicated; invalid examples are dropped. Output is JSONL with
17
+ OpenAI `messages` + `tools` columns, and optionally the xlam single-turn format
18
+ in a second file.
19
+
20
+ Usage:
21
+ export HF_TOKEN=hf_...
22
+ python generate_function_calling.py --size 2000 --format both \
23
+ --out data/messages.jsonl --push-repo Surfdan/glm53-flash-function-calling
24
+ """
25
+
26
+ import argparse
27
+ import json
28
+ import os
29
+ import random
30
+ import re
31
+ import sys
32
+ import threading
33
+ import time
34
+ from concurrent.futures import ThreadPoolExecutor, as_completed
35
+
36
+ from openai import OpenAI
37
+
38
+ MODEL = "zai-org/GLM-5.3-Flash"
39
+ BASE_URL = "https://router.huggingface.co/v1"
40
+
41
+ SYSTEM_WITH_TOOLS = (
42
+ "You are a helpful assistant with access to the tools provided. "
43
+ "Use them whenever they help answer the user's request, and give a direct "
44
+ "answer without tools when they are not needed."
45
+ )
46
+
47
+ DOMAINS = {
48
+ "weather": ["weather forecasts", "severe alerts", "historical climate data", "air quality"],
49
+ "travel": ["flight search", "hotel booking", "car rental", "itinerary planning"],
50
+ "finance": ["stock quotes", "currency conversion", "loan calculators", "budget tracking"],
51
+ "ecommerce": ["product search", "order tracking", "price alerts", "returns and refunds"],
52
+ "calendar": ["scheduling", "reminders", "meeting-room booking", "time zones"],
53
+ "devops": ["server monitoring", "deployments", "log search", "incident paging"],
54
+ "crm": ["contact lookup", "deal stages", "email logging", "lead scoring"],
55
+ "smarthome": ["lighting", "thermostats", "security cameras", "kitchen appliances"],
56
+ "media": ["movie lookup", "playlists", "podcast search", "subtitle handling"],
57
+ "food": ["recipe search", "restaurant reservations", "nutrition tracking", "grocery lists"],
58
+ "fitness": ["workout logs", "step counts", "heart-rate data", "race training plans"],
59
+ "realestate": ["listing search", "mortgage estimates", "comparable sales", "open houses"],
60
+ "logistics": ["shipment tracking", "fleet routing", "warehouse inventory", "customs documents"],
61
+ "education": ["course catalogs", "quiz generation", "grade books", "study plans"],
62
+ "hr": ["leave requests", "payroll", "org charts", "candidate pipelines"],
63
+ "productivity": ["notes", "todo lists", "document search", "file conversion"],
64
+ }
65
+
66
+ # Example-type mix: negatives teach the model NOT to call tools.
67
+ TYPE_WEIGHTS = {"tool": 0.85, "no_tool": 0.15}
68
+
69
+ _rate_lock = threading.Lock()
70
+
71
+
72
+ def chat(client, **kwargs):
73
+ """Chat completion with exponential backoff. Returns the message or None."""
74
+ for attempt in range(6):
75
+ try:
76
+ resp = client.chat.completions.create(**kwargs)
77
+ return resp.choices[0].message
78
+ except Exception as e: # noqa: BLE001 - provider errors are heterogeneous
79
+ wait = min(60.0, 2.0 ** attempt * 1.5)
80
+ print(f"[warn] {type(e).__name__}: {e} — retry {attempt + 1} in {wait:.0f}s", flush=True)
81
+ time.sleep(wait)
82
+ return None
83
+
84
+
85
+ def extract_json(text):
86
+ """Pull the first JSON object/array out of a model reply."""
87
+ if text is None:
88
+ return None
89
+ m = re.search(r"\{.*\}|\[.*\]", text, re.DOTALL)
90
+ if not m:
91
+ return None
92
+ for candidate in (m.group(0),):
93
+ try:
94
+ return json.loads(candidate)
95
+ except json.JSONDecodeError:
96
+ continue
97
+ return None
98
+
99
+
100
+ def valid_function(f):
101
+ if not isinstance(f, dict):
102
+ return False
103
+ name, params = f.get("name"), f.get("parameters")
104
+ return (
105
+ isinstance(name, str)
106
+ and re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_]{1,63}", name) is not None
107
+ and isinstance(params, dict)
108
+ and isinstance(params.get("properties"), dict)
109
+ and len(params["properties"]) > 0
110
+ )
111
+
112
+
113
+ def args_valid(func, args):
114
+ """Check parsed arguments against the function's JSON schema (loose but useful)."""
115
+ if not isinstance(args, dict):
116
+ return False
117
+ props = func["parameters"].get("properties", {})
118
+ required = func["parameters"].get("required", [])
119
+ if not set(required).issubset(args):
120
+ return False
121
+ if not set(args).issubset(props):
122
+ return False
123
+ type_map = {"string": str, "number": (int, float), "integer": int,
124
+ "boolean": bool, "array": list, "object": dict}
125
+ for k, v in args.items():
126
+ t = props.get(k, {}).get("type")
127
+ if t == "number" and isinstance(v, bool):
128
+ return False
129
+ if t in type_map and not isinstance(v, type_map[t]):
130
+ return False
131
+ return True
132
+
133
+
134
+ def norm_tool_calls(message):
135
+ calls = []
136
+ for i, tc in enumerate(message.tool_calls or []):
137
+ calls.append({
138
+ "id": getattr(tc, "id", None) or f"call_{i}",
139
+ "type": "function",
140
+ "function": {"name": tc.function.name, "arguments": tc.function.arguments},
141
+ })
142
+ return calls
143
+
144
+
145
+ def build_example(client, rng, domain, hints, ex_type):
146
+ n_funcs = rng.randint(3, 6)
147
+ tool_rule = (
148
+ "The user's request must be answerable WITHOUT any of these functions "
149
+ "(the assistant should reply directly)."
150
+ if ex_type == "no_tool" else
151
+ "The user's request should naturally require calling at least one of the functions."
152
+ )
153
+ scen_prompt = f"""Design one realistic function-calling scenario in the domain "{domain}" (topics: {', '.join(hints)}).
154
+
155
+ Return ONLY a JSON object with these keys:
156
+ {{
157
+ "scenario": "one sentence describing the app/context where this assistant operates",
158
+ "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.]
159
+ "user_query": "a natural user request that a real user would send. {tool_rule}"
160
+ }}
161
+
162
+ Requirements:
163
+ - Function names are snake_case and domain-appropriate. Vary parameter types (strings, numbers, enums, arrays, objects).
164
+ - The user query is 1-3 sentences, informal, with concrete details (names, dates, numbers). Never mention the function names.
165
+ - Be creative and specific; avoid generic templates."""
166
+ scen_msg = chat(client, model=MODEL, temperature=1.0, max_tokens=1600,
167
+ messages=[{"role": "user", "content": scen_prompt}])
168
+ scen = extract_json(scen_msg.content if scen_msg else None)
169
+ if not isinstance(scen, dict):
170
+ return None
171
+ funcs = [f for f in scen.get("functions", []) if valid_function(f)]
172
+ if len(funcs) < 3 or not scen.get("user_query"):
173
+ return None
174
+ query = str(scen["user_query"]).strip()
175
+
176
+ # --- Stage B: generate the assistant's tool calls -------------------------
177
+ stage_b_msgs = [{"role": "system", "content": SYSTEM_WITH_TOOLS},
178
+ {"role": "user", "content": query}]
179
+ resp = chat(client, model=MODEL, temperature=0.7, max_tokens=700,
180
+ messages=stage_b_msgs,
181
+ tools=funcs,
182
+ tool_choice="required" if ex_type == "tool" else "auto")
183
+ if resp is None:
184
+ return None
185
+ calls = norm_tool_calls(resp)
186
+
187
+ if ex_type == "no_tool":
188
+ if calls: # model called tools anyway — keep it as a tool example
189
+ ex_type = "tool"
190
+ else:
191
+ content = (resp.content or "").strip()
192
+ if len(content) < 10:
193
+ return None
194
+ return {"messages": [
195
+ {"role": "system", "content": SYSTEM_WITH_TOOLS},
196
+ {"role": "user", "content": query},
197
+ {"role": "assistant", "content": content}],
198
+ "tools": funcs, "type": "no_tool", "domain": domain}
199
+
200
+ # Validate and parse every call's arguments against its schema.
201
+ parsed = []
202
+ for tc in calls:
203
+ try:
204
+ args = json.loads(tc["function"]["arguments"])
205
+ except json.JSONDecodeError:
206
+ args = None
207
+ func = next((f for f in funcs if f["name"] == tc["function"]["name"]), None)
208
+ if func is None or not args_valid(func, args):
209
+ continue
210
+ parsed.append((tc, args))
211
+ if not parsed:
212
+ return None
213
+
214
+ # --- Stage C: simulate plausible tool results -----------------------------
215
+ call_desc = "\n".join(
216
+ f"{i + 1}. {tc['function']['name']}({json.dumps(args, ensure_ascii=False)})"
217
+ for i, (tc, args) in enumerate(parsed))
218
+ sim_prompt = f"""You are simulating the backends for these functions:
219
+ {json.dumps(funcs, indent=1)}
220
+
221
+ The assistant made these calls:
222
+ {call_desc}
223
+
224
+ Return ONLY a JSON array with one object per call, IN ORDER, that each function
225
+ would realistically return given its arguments. Match each function's implied
226
+ return shape. Include realistic values (IDs, timestamps, statuses), not placeholders."""
227
+ sim_msg = chat(client, model=MODEL, temperature=0.7, max_tokens=1200,
228
+ messages=[{"role": "user", "content": sim_prompt}])
229
+ results = extract_json(sim_msg.content if sim_msg else None)
230
+ if not isinstance(results, list) or len(results) != len(parsed):
231
+ return None
232
+
233
+ tool_msgs = [{"role": "tool", "tool_call_id": tc["id"], "name": tc["function"]["name"],
234
+ "content": json.dumps(res)} for (tc, _), res in zip(parsed, results)]
235
+
236
+ # --- Stage D: final assistant answer with results in context --------------
237
+ final_msgs = [{"role": "system", "content": SYSTEM_WITH_TOOLS},
238
+ {"role": "user", "content": query},
239
+ {"role": "assistant", "content": None, "tool_calls": [tc for tc, _ in parsed]},
240
+ *tool_msgs]
241
+ final = chat(client, model=MODEL, temperature=0.7, max_tokens=500, messages=final_msgs)
242
+ if final is None or not (final.content or "").strip():
243
+ return None
244
+
245
+ messages = [{"role": "system", "content": SYSTEM_WITH_TOOLS},
246
+ {"role": "user", "content": query},
247
+ {"role": "assistant", "content": None, "tool_calls": [tc for tc, _ in parsed]},
248
+ *tool_msgs,
249
+ {"role": "assistant", "content": final.content.strip()}]
250
+ return {"messages": messages, "tools": funcs, "type": "tool",
251
+ "n_calls": len(parsed), "domain": domain}
252
+
253
+
254
+ def worker(client, rng, out_files, lock, state, args):
255
+ while state["success"] < args.size:
256
+ if state["success"] + state["pending"] >= args.size + 200:
257
+ return # enough in flight
258
+ with state["lock"]:
259
+ state["pending"] += 1
260
+ domain = rng.choice(list(DOMAINS))
261
+ ex_type = rng.choices(list(TYPE_WEIGHTS), weights=list(TYPE_WEIGHTS.values()))[0]
262
+ rec = build_example(client, rng, domain, DOMAINS[domain], ex_type)
263
+ with state["lock"]:
264
+ state["pending"] -= 1
265
+ if rec is None:
266
+ state["fail"] += 1
267
+ continue
268
+ qhash = hash(rec["messages"][1]["content"])
269
+ if qhash in state["seen"]:
270
+ state["fail"] += 1
271
+ continue
272
+ state["seen"].add(qhash)
273
+ rec["id"] = f"{args.seed_id}-{state['success'] + 1:06d}"
274
+ for fmt in args._formats:
275
+ row = to_row(rec, fmt)
276
+ out_files[fmt].write(json.dumps(row, ensure_ascii=False) + "\n")
277
+ out_files[fmt].flush()
278
+ state["success"] += 1
279
+ if state["success"] % 25 == 0:
280
+ print(f"[progress] {state['success']}/{args.size} "
281
+ f"(fail={state['fail']})", flush=True)
282
+ if args.trackio:
283
+ log_progress(args, state)
284
+
285
+
286
+ def to_row(rec, fmt):
287
+ if fmt == "messages":
288
+ return {"id": rec["id"], "messages": rec["messages"], "tools": rec["tools"],
289
+ "domain": rec["domain"], "type": rec["type"]}
290
+ answers = []
291
+ if rec["type"] == "tool":
292
+ m = rec["messages"][2]
293
+ for tc in m["tool_calls"]:
294
+ answers.append({"name": tc["function"]["name"],
295
+ "arguments": json.loads(tc["function"]["arguments"])})
296
+ return {"id": rec["id"], "query": rec["messages"][1]["content"],
297
+ "tools": rec["tools"], "answers": answers}
298
+
299
+
300
+ def log_progress(args, state):
301
+ try:
302
+ import trackio
303
+ if not getattr(log_progress, "_init", False):
304
+ trackio.init(project="glm53-flash-function-calling",
305
+ space_id=os.environ.get("TRACKIO_SPACE_ID"))
306
+ log_progress._init = True
307
+ trackio.log({"examples": state["success"], "failures": state["fail"]},
308
+ step=state["success"])
309
+ except Exception as e: # noqa: BLE001 - metrics must never kill the run
310
+ print(f"[warn] trackio: {e}", flush=True)
311
+
312
+
313
+ def main():
314
+ ap = argparse.ArgumentParser(description=__doc__)
315
+ ap.add_argument("--size", type=int, default=2000, help="number of validated examples")
316
+ ap.add_argument("--out", default="data", help="output directory for JSONL files")
317
+ ap.add_argument("--format", choices=["messages", "xlam", "both"], default="messages")
318
+ ap.add_argument("--workers", type=int, default=8)
319
+ ap.add_argument("--provider", default=None, help="pin a provider, e.g. novita")
320
+ ap.add_argument("--push-repo", default=None, help="upload results to this dataset repo")
321
+ ap.add_argument("--seed-id", default="glm53fc")
322
+ args = ap.parse_args()
323
+ args.trackio = bool(os.environ.get("TRACKIO_SPACE_ID"))
324
+
325
+ os.makedirs(args.out, exist_ok=True)
326
+ formats = ["messages", "xlam"] if args.format == "both" else [args.format]
327
+ paths = {fmt: os.path.join(args.out, f"{fmt}.jsonl") for fmt in formats}
328
+
329
+ model = MODEL if args.provider is None else f"{MODEL}:{args.provider}"
330
+ token = os.environ.get("HF_TOKEN")
331
+ assert token, "HF_TOKEN must be set (a token with Inference Providers access)"
332
+ client = OpenAI(base_url=BASE_URL, api_key=token)
333
+
334
+ # Smoke-check: the model id must resolve before generating anything.
335
+ ping = chat(client, model=model, max_tokens=5,
336
+ messages=[{"role": "user", "content": "Say OK."}])
337
+ assert ping is not None, f"{model} did not respond through the router"
338
+ print(f"[ok] {model} reachable — starting generation", flush=True)
339
+
340
+ state = {"success": 0, "fail": 0, "pending": 0, "lock": threading.Lock(),
341
+ "seen": set(), "rng": random.Random(20260925)}
342
+ out_files = {}
343
+ for fmt, path in paths.items():
344
+ if os.path.exists(path): # resume: keep existing rows, restore dedup set
345
+ with open(path) as f:
346
+ for line in f:
347
+ try:
348
+ state["seen"].add(hash(json.loads(line)["query"]))
349
+ except Exception:
350
+ pass
351
+ print(f"[resume] {path} exists — appending after dedup against it", flush=True)
352
+ out_files[fmt] = open(path, "a", encoding="utf-8")
353
+
354
+ rng = random.Random(20260925)
355
+ with ThreadPoolExecutor(max_workers=args.workers) as pool:
356
+ futures = [pool.submit(worker, client, rng, out_files, None, state, args)
357
+ for _ in range(args.workers)]
358
+ for f in as_completed(futures):
359
+ f.result()
360
+
361
+ for f in out_files.values():
362
+ f.close()
363
+ print(f"[done] {state['success']} examples, {state['fail']} dropped", flush=True)
364
+ assert state["success"] >= args.size * 0.8, "yield was too low — inspect warnings above"
365
+
366
+ if args.push_repo:
367
+ from huggingface_hub import HfApi
368
+ api = HfApi(token=token)
369
+ for fmt, path in paths.items():
370
+ api.upload_file(path_or_fileobj=path, path_in_repo=f"data/{os.path.basename(path)}",
371
+ repo_id=args.push_repo, repo_type="dataset",
372
+ commit_message=f"Add {fmt} split ({state['success']} examples)")
373
+ print(f"[pushed] https://huggingface.co/datasets/{args.push_repo}", flush=True)
374
+
375
+
376
+ if __name__ == "__main__":
377
+ main()