"""Readers that convert open function-calling datasets into one OpenAI/HF-style schema, plus helpers to feed rows of the `tools` config into `tokenizer.apply_chat_template`. Stored row (Parquet-friendly): messages: [{role, content, tool_calls (JSON string or ""), tool_call_id, name}] tools: JSON string with a list of {"type": "function", "function": {...}} """ import ast import json import re import uuid def to_chat_template(row): """Decode a stored row into (messages, tools) for tokenizer.apply_chat_template(messages, tools=tools).""" msgs = [] for m in row["messages"]: out = {"role": m["role"], "content": m["content"]} if m.get("tool_calls"): out["tool_calls"] = json.loads(m["tool_calls"]) if m.get("tool_call_id"): out["tool_call_id"] = m["tool_call_id"] if m.get("name"): out["name"] = m["name"] msgs.append(out) return msgs, json.loads(row["tools"]) def encode_messages(messages): """Inverse of to_chat_template for storage.""" out = [] for m in messages: out.append({"role": m["role"], "content": m.get("content") or "", "tool_calls": json.dumps(m["tool_calls"], ensure_ascii=False) if m.get("tool_calls") else "", "tool_call_id": m.get("tool_call_id", ""), "name": m.get("name", "")}) return out def _norm_tool(t): if isinstance(t, dict) and "function" in t: return {"type": "function", "function": t["function"]} if isinstance(t, dict) and "name" in t: return {"type": "function", "function": {k: t[k] for k in ("name", "description", "parameters") if k in t}} raise ValueError("bad tool") def _call(name, args, i): return {"id": f"call_{i}", "type": "function", "function": {"name": name, "arguments": args}} def valid(messages, tools): """Structural checks: alternating roles, every tool call names a declared tool, tool results follow calls.""" names = {t["function"]["name"] for t in tools} if not messages or messages[0]["role"] != "user" or messages[-1]["role"] != "assistant": return False pending = 0 if messages[-1].get("tool_calls"): # single-turn call datasets end with the call itself messages = messages + [{"role": "tool"}] * len(messages[-1]["tool_calls"]) + [{"role": "assistant", "content": "."}] for m in messages: if m["role"] == "assistant" and m.get("tool_calls"): if any(tc["function"]["name"] not in names or not isinstance(tc["function"]["arguments"], dict) for tc in m["tool_calls"]): return False pending = len(m["tool_calls"]) elif m["role"] == "tool": if pending <= 0: return False pending -= 1 elif m["role"] == "assistant" and not (m.get("content") or "").strip(): return False return pending == 0 # ------------------------------------------------------------------ Hermes function calling v1 _TOOLS_XML = re.compile(r"\s*(.*?)\s*", re.S) _CALL_XML = re.compile(r"\s*(.*?)\s*", re.S) _RESP_XML = re.compile(r"\s*(.*?)\s*", re.S) def _loads_loose(s): try: return json.loads(s) except ValueError: return ast.literal_eval(s) def read_hermes(row): conv = row["conversations"] sys_msg = next((m["value"] for m in conv if m["from"] == "system"), "") blocks = [b for b in _TOOLS_XML.findall(sys_msg) if b.strip()] if not blocks: return None raw = _loads_loose(max(blocks, key=len)) tools = [_norm_tool(t) for t in (raw if isinstance(raw, list) else [raw])] msgs, n, queue = [], 0, [] for turn in conv: if turn["from"] == "system": continue v = turn["value"] if turn["from"] == "human": msgs.append({"role": "user", "content": v}) elif turn["from"] == "gpt": calls = _CALL_XML.findall(v) if calls: tcs = [] for c in calls: obj = _loads_loose(c) n += 1 tcs.append(_call(obj["name"], obj.get("arguments", {}), n)) queue = [tc for tc in tcs] text = _CALL_XML.sub("", v).strip() msgs.append({"role": "assistant", "content": text, "tool_calls": tcs}) else: msgs.append({"role": "assistant", "content": v}) elif turn["from"] == "tool": for resp in _RESP_XML.findall(v) or [v]: tc = queue.pop(0) if queue else None if tc is None: return None try: content = json.dumps(_loads_loose(resp).get("content", _loads_loose(resp)), ensure_ascii=False) except (ValueError, SyntaxError, AttributeError): content = resp msgs.append({"role": "tool", "tool_call_id": tc["id"], "name": tc["function"]["name"], "content": content}) return msgs, tools # ------------------------------------------------------------------ ToolACE ([Func A(x=1), Func B(y="z")]) def _split_calls(s, names=()): s = s.strip() if not (s.startswith("[") and s.endswith("]")): return None s, out, depth, quote, start = s[1:-1], [], 0, None, 0 for i, ch in enumerate(s): if quote: if ch == quote and s[i - 1] != "\\": quote = None elif ch in "\"'": quote = ch elif ch in "([{": depth += 1 elif ch in ")]}": depth -= 1 elif ch == "," and depth == 0: out.append(s[start:i]) start = i + 1 out.append(s[start:]) calls = [] for c in out: c = c.strip() if not c.endswith(")"): return None found = None for p in [i for i, ch in enumerate(c) if ch == "("]: name = c[:p].strip() if names and name not in names: continue try: tree = ast.parse("f" + c[p:], mode="eval").body except SyntaxError: continue if isinstance(tree, ast.Call) and not tree.args: found = (name, {kw.arg: ast.literal_eval(kw.value) for kw in tree.keywords}) break if not found: return None calls.append(found) return calls def read_toolace(row): sysm = row["system"] j = sysm.find("[", sysm.find("JSON format")) try: tools_raw, _ = json.JSONDecoder().raw_decode(sysm[j:]) tools = [_norm_tool(t) for t in tools_raw] except (ValueError, KeyError): return None msgs, n, queue = [], 0, [] for turn in row["conversations"]: v = turn["value"] if turn["from"] == "user": msgs.append({"role": "user", "content": v}) elif turn["from"] == "assistant": try: calls = (_split_calls(v, {t["function"]["name"] for t in tools}) if v.strip().startswith("[") else None) except (SyntaxError, ValueError): calls = None if calls: tcs = [] for name, args in calls: n += 1 tcs.append(_call(name, args, n)) queue = list(tcs) msgs.append({"role": "assistant", "content": "", "tool_calls": tcs}) else: msgs.append({"role": "assistant", "content": v}) elif turn["from"] == "tool": try: results = json.loads(v) except ValueError: return None results = results if isinstance(results, list) else [results] for res in results: if not queue: return None tc = queue.pop(0) payload = res.get("results", res) if isinstance(res, dict) else res msgs.append({"role": "tool", "tool_call_id": tc["id"], "name": tc["function"]["name"], "content": json.dumps(payload, ensure_ascii=False)}) return msgs, tools # ------------------------------------------------------------------ Glaive function calling v2 _GL_TURN = re.compile(r"(USER:|ASSISTANT:|FUNCTION RESPONSE:)") def read_glaive(row): sysm = row["system"].replace("SYSTEM:", "", 1) tools, dec, s = [], json.JSONDecoder(), sysm i = s.find("{") while i != -1: try: obj, end = dec.raw_decode(s[i:]) except ValueError: break tools.append(_norm_tool(obj)) i = s.find("{", i + end) parts = _GL_TURN.split(row["chat"]) msgs, n, queue = [], 0, [] for tag, text in zip(parts[1::2], parts[2::2]): text = text.replace("<|endoftext|>", "").strip() if tag == "USER:": msgs.append({"role": "user", "content": text}) elif tag == "ASSISTANT:": if text.startswith(""): body = text[len(""):].strip() m = re.match(r'\{"name":\s*"([^"]+)",\s*"arguments":\s*\'(.*)\'\}\s*$', body, re.S) if not m: return None try: args = json.loads(m.group(2)) except ValueError: return None n += 1 tc = _call(m.group(1), args, n) queue = [tc] msgs.append({"role": "assistant", "content": "", "tool_calls": [tc]}) else: msgs.append({"role": "assistant", "content": text}) else: if not queue: return None tc = queue.pop(0) msgs.append({"role": "tool", "tool_call_id": tc["id"], "name": tc["function"]["name"], "content": text}) if not tools: return None return msgs, tools # ------------------------------------------------------------------ template-independent (Hermes-style) rendering HERMES_SYSTEM = ( "You are a helpful assistant with access to the following tools. Call a tool only when it is needed. " "To call a tool, reply with one block per call, each containing a JSON object with " "\"name\" and \"arguments\". Tool results are returned inside blocks.\n\n" "\n{tools}\n" ) def hermes_system_prompt(tools): return HERMES_SYSTEM.format(tools="\n".join(json.dumps(t, ensure_ascii=False) for t in tools)) def to_hermes_messages(row, system_prefix=""): """Render a `tools` row as plain {role, content} messages (system / user / assistant only). Works with ANY chat template (Qwen, Llama, Gemma, Mistral, Phi, ...), keeps assistant-only loss possible, and matches `agent_tools.parse_tool_calls` at inference time. Tool results become a user turn with blocks; parallel results are merged into one turn. """ msgs, tools = to_chat_template(row) out = [{"role": "system", "content": (system_prefix + "\n\n" if system_prefix else "") + hermes_system_prompt(tools)}] for m in msgs: if m["role"] == "assistant" and m.get("tool_calls"): calls = "\n".join("\n" + json.dumps({"name": tc["function"]["name"], "arguments": tc["function"]["arguments"]}, ensure_ascii=False) + "\n" for tc in m["tool_calls"]) out.append({"role": "assistant", "content": ((m.get("content") or "").strip() + "\n" + calls).strip()}) elif m["role"] == "tool": block = f"\n{m['content']}\n" if out[-1]["role"] == "user" and out[-1]["content"].startswith(""): out[-1]["content"] += "\n" + block else: out.append({"role": "user", "content": block}) else: out.append({"role": m["role"], "content": m.get("content") or ""}) return out