File size: 5,713 Bytes
a653623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""Probe an mlx-vlm server's Inkling 2 tool-call handling with the real model: complete, parallel, cut-off calls.

Usage: upstream_probe.py <base_url> <model_id> <out.json> [case1,case2]
Each case is sent streamed and not streamed. A cut-off call is forced with a small max_tokens on a long write_file.
"""

import json
import os
import sys
import urllib.error
import urllib.request

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from scenarios import TOOLS  # noqa: E402

WEATHER = {"type": "function", "function": {
    "name": "get_weather", "description": "Current weather for a city.",
    "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}

CASES = {
    "single": dict(messages=[{"role": "user", "content": "What is the weather in Oslo right now?"}],
                   tools=[WEATHER], max_tokens=400),
    "parallel": dict(messages=[{"role": "user", "content": "Compare the weather in Oslo and Lisbon right now."}],
                     tools=[WEATHER], max_tokens=500),
    "text_then_call": dict(messages=[{"role": "user", "content":
                           "First tell me in one short sentence what you are about to do, then look up the weather in Oslo."}],
                           tools=[WEATHER], max_tokens=500),
    "cut_off_call": dict(messages=[{"role": "user", "content":
                         "Use write_file to save a 60-line Python script that prints a multiplication table to table.py."}],
                         tools=[TOOLS["write_file"]], max_tokens=120),
    # No reasoning, so the token limit falls inside the call's JSON.
    "cut_off_in_call": dict(messages=[{"role": "user", "content":
                            "Use write_file to save a 60-line Python script that prints a multiplication table to table.py."}],
                            tools=[TOOLS["write_file"]], max_tokens=60, reasoning_effort="none"),
    # A file far longer than the limit, with room for the reasoning first: the limit falls inside the call.
    "cut_off_long": dict(messages=[{"role": "user", "content":
                         "Use write_file to save notes.md with a detailed 1500-word guide to baking sourdough bread. "
                         "Call the tool straight away."}],
                         tools=[TOOLS["write_file"]], max_tokens=350),
    # The prompt on which the original checkpoint writes a call with a missing quote at greedy decoding.
    "malformed_call": dict(messages=[{"role": "user", "content":
                           "Find customer C-88's shipped orders over 100 dollars that are tagged gift."}],
                           tools=[TOOLS["search_orders"]], max_tokens=500),
}


def post(base, body):
    req = urllib.request.Request(base.rstrip("/") + "/chat/completions", data=json.dumps(body).encode(),
                                 headers={"content-type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=900) as r:
            return r.status, r.read().decode()
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()


def summarize(status, raw, stream):
    out = {"http": status}
    if not stream:
        try:
            choice = json.loads(raw)["choices"][0]
        except (ValueError, KeyError):
            return {**out, "body": raw[:400]}
        m = choice["message"]
        calls = [(c["function"]["name"], c["function"]["arguments"][:80]) for c in m.get("tool_calls") or []]
        return {**out, "finish": choice.get("finish_reason"), "content": m.get("content"),
                "reasoning": bool(m.get("reasoning_content") or m.get("reasoning")), "calls": calls}
    content, calls, finish, errors, reasoning = "", {}, [], [], False
    for line in raw.splitlines():
        if not line.startswith("data: ") or line == "data: [DONE]":
            continue
        try:
            event = json.loads(line[6:])
        except ValueError:
            errors.append(line[:200]); continue
        if "error" in event:
            errors.append(json.dumps(event["error"])[:300]); continue
        for choice in event.get("choices") or []:
            delta = choice.get("delta") or {}
            content += delta.get("content") or ""
            reasoning = reasoning or bool(delta.get("reasoning_content") or delta.get("reasoning"))
            for c in delta.get("tool_calls") or []:
                e = calls.setdefault(c.get("index", 0), {"name": "", "arguments": ""})
                e["name"] += c["function"].get("name") or ""
                e["arguments"] += c["function"].get("arguments") or ""
            if choice.get("finish_reason"):
                finish.append(choice["finish_reason"])
    return {**out, "finish": finish, "content": content or None, "reasoning": reasoning,
            "calls": [(c["name"], c["arguments"][:80]) for c in calls.values()], "errors": errors}


def main():
    base, model, out_path = sys.argv[1:4]
    only = sys.argv[4].split(",") if len(sys.argv) > 4 else list(CASES)
    results = {}
    for name, case in CASES.items():
        if name not in only:
            continue
        for stream in (False, True):
            body = {"model": model, "temperature": 0.0, "reasoning_effort": "low", "stream": stream, **case}
            status, raw = post(base, body)
            results[f"{name}/{'stream' if stream else 'plain'}"] = r = summarize(status, raw, stream)
            print(name, "stream" if stream else "plain", json.dumps(r, ensure_ascii=False)[:600], flush=True)
    os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
    json.dump(results, open(out_path, "w"), indent=1, ensure_ascii=False)


if __name__ == "__main__":
    main()