File size: 1,841 Bytes
e8eb104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tool-call calibration conversations: NousResearch/hermes-function-calling-v1 (func-calling.json,
rev dae3e1d), parsed into structured tool_calls and rendered through the model's own chat template
with tools=, so the Hessians see the served <tools> system prompt and <tool_call><function=...> turns.
No BFCL data. Import render(tok, path) -> list of rendered strings, in file order."""
import json, re

CALL = re.compile(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", re.S)
RESP = re.compile(r"<tool_response>\s*(.*?)\s*</tool_response>", re.S)


def convert(r):
    tools = json.loads(r["tools"]) if isinstance(r["tools"], str) else r["tools"]
    msgs = []
    for m in r["conversations"]:
        v = m["value"]
        if m["from"] == "system":
            continue  # the template writes its own tools system prompt
        if m["from"] == "human":
            msgs.append({"role": "user", "content": v})
        elif m["from"] == "gpt":
            calls = [json.loads(c) for c in CALL.findall(v)]
            if calls:
                msgs.append({"role": "assistant", "content": CALL.sub("", v).strip(),
                             "tool_calls": [{"type": "function", "function": {"name": c["name"], "arguments": c.get("arguments", {})}} for c in calls]})
            else:
                msgs.append({"role": "assistant", "content": v})
        elif m["from"] == "tool":
            for body in RESP.findall(v) or [v]:
                msgs.append({"role": "tool", "content": body})
    return tools, msgs


def render(tok, path, **kw):
    out = []
    for r in json.load(open(path)):
        try:
            tools, msgs = convert(r)
            out.append(tok.apply_chat_template(msgs, tools=tools, tokenize=False, **kw))
        except (ValueError, KeyError, TypeError, json.JSONDecodeError):
            continue
    return out