okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-028-tools-p1b82d1d456

main
8.8 KiB161 linesraw
1"""#4427, #4077, #4078 through the HTTP routes: what a client gets for the damaged calls and the stray closing think tag.
2
3The model's text is replayed by the mock engine; the reply is read from Chat Completions, the Anthropic Messages API and
4the Responses API, each whole and streamed.  Every route must hand over the same calls with the same arguments.
5
6    python -m unittest serve.test_tool_routes -v
7"""
8from __future__ import annotations
9
10import contextlib
11import http.client
12import io
13import json
14import sys
15import unittest
16from pathlib import Path
17
18sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
19from serve.frontend import ChatTemplate  # noqa: E402
20from serve.server import ByteTokenizer, MockEngine, Service, serve  # noqa: E402
21
22ROOT = Path(__file__).resolve().parents[1]
23TEMPLATE = ChatTemplate(ROOT / "serve/chat_template.jinja")
24PROPS = {"todos": {"type": "array"}, "path": {"type": "string"}, "content": {"type": "string"}}
25NAMES = ("todo_write", "write_file")
26
27
28def call(name, **params):
29    body = "".join(f"<parameter={k}>\n{v}\n</parameter>\n" for k, v in params.items())
30    return f"<tool_call>\n<function={name}>\n{body}</function>\n</tool_call>"
31
32
33class Routes(unittest.TestCase):
34    def read(self, script, **service):
35        """{route: (finish, [(name, arguments)], answer text)} for the model's `script`, on every route."""
36        tok = ByteTokenizer()
37        svc = Service(MockEngine(tok, script, max_context=16384), tok, TEMPLATE)
38        for k, v in service.items():
39            setattr(svc, k, v)
40        httpd = serve(svc, port=0)
41        port = httpd.server_address[1]
42        out = {}
43
44        def post(path, body):
45            c = http.client.HTTPConnection("127.0.0.1", port, timeout=60)
46            try:
47                with contextlib.redirect_stdout(io.StringIO()):
48                    c.request("POST", path, body=json.dumps(body).encode(),
49                              headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"})
50                    return c.getresponse().read().decode()
51            finally:
52                c.close()
53
54        def sse(raw):
55            return [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")]
56
57        chat_tools = [{"type": "function", "function": {"name": n, "parameters": {"type": "object", "properties": PROPS}}}
58                      for n in NAMES]
59        try:
60            for stream in (False, True):
61                raw = post("/v1/chat/completions", {"model": "x", "max_tokens": 900, "stream": stream, "tools": chat_tools,
62                                                    "messages": [{"role": "user", "content": "go"}]})
63                if stream:
64                    evs, calls, text, finish = sse(raw), {}, "", None
65                    for e in evs:
66                        ch = e["choices"][0]
67                        text += ch["delta"].get("content") or ""
68                        finish = ch.get("finish_reason") or finish
69                        for tc in ch["delta"].get("tool_calls") or []:
70                            slot = calls.setdefault(tc["index"], {"name": None, "args": ""})
71                            slot["name"] = (tc.get("function") or {}).get("name") or slot["name"]
72                            slot["args"] += (tc.get("function") or {}).get("arguments") or ""
73                    got = [(c["name"], json.loads(c["args"])) for _, c in sorted(calls.items())]
74                else:
75                    d = json.loads(raw)["choices"][0]
76                    text, finish = d["message"].get("content") or "", d["finish_reason"]
77                    got = [(t["function"]["name"], json.loads(t["function"]["arguments"])) for t in d["message"].get("tool_calls") or []]
78                out["chat", stream] = (finish, got, text.strip())
79
80                raw = post("/v1/messages", {"model": "x", "max_tokens": 900, "stream": stream,
81                                            "tools": [{"name": n, "input_schema": {"type": "object", "properties": PROPS}} for n in NAMES],
82                                            "messages": [{"role": "user", "content": "go"}]})
83                if stream:
84                    evs, blocks, text, finish = sse(raw), {}, "", None
85                    for e in evs:
86                        if e["type"] == "content_block_start" and e["content_block"]["type"] == "tool_use":
87                            blocks[e["index"]] = {"name": e["content_block"]["name"], "json": ""}
88                        elif e["type"] == "content_block_delta":
89                            if e["delta"]["type"] == "input_json_delta":
90                                blocks[e["index"]]["json"] += e["delta"]["partial_json"]
91                            elif e["delta"]["type"] == "text_delta":
92                                text += e["delta"]["text"]
93                        elif e["type"] == "message_delta":
94                            finish = e["delta"]["stop_reason"]
95                    got = [(b["name"], json.loads(b["json"] or "{}")) for _, b in sorted(blocks.items())]
96                else:
97                    d = json.loads(raw)
98                    finish = d["stop_reason"]
99                    text = "".join(b.get("text", "") for b in d["content"] if b["type"] == "text")
100                    got = [(b["name"], b["input"]) for b in d["content"] if b["type"] == "tool_use"]
101                out["anthropic", stream] = (finish, got, text.strip())
102
103                raw = post("/v1/responses", {"model": "x", "input": "go", "stream": stream, "store": False,
104                                             "tools": [{"type": "function", "name": n, "parameters": {"type": "object", "properties": PROPS}}
105                                                       for n in NAMES]})
106                if stream:
107                    items = [e["item"] for e in sse(raw) if e["type"] == "response.output_item.done"]
108                else:
109                    items = json.loads(raw)["output"]
110                got = [(i["name"], json.loads(i["arguments"])) for i in items if i["type"] == "function_call"]
111                text = "".join(c["text"] for i in items if i["type"] == "message" for c in i["content"] if c["type"] == "output_text")
112                out["responses", stream] = ("-", got, text.strip())
113        finally:
114            httpd.shutdown()
115            httpd.server_close()
116        return out
117
118    def every_route(self, script, calls, text="", finish=("tool_calls", "tool_use"), **service):
119        got = self.read(script, **service)
120        for (route, stream), (fin, got_calls, got_text) in got.items():
121            with self.subTest(route=route, stream=stream):
122                self.assertEqual(got_calls, calls)
123                self.assertEqual(got_text, text)
124                if route == "chat":
125                    self.assertEqual(fin, finish[0])
126                elif route == "anthropic":
127                    self.assertEqual(fin, finish[1])
128
129    def test_a_damaged_array_argument_arrives_as_the_array(self):
130        stray = ('[{"content": "Init", "status": "in_progress", "pending": false}, '
131                 '{"content": "Write", "status": "pending", "in_progress", "pending": false}]')
132        want = [{"content": "Init", "status": "in_progress", "pending": False},
133                {"content": "Write", "status": "pending", "pending": False}]
134        self.every_route("Plan.\n</think>\n\n" + call("todo_write", todos=stray), [("todo_write", {"todos": want})])
135
136    def test_a_call_without_its_function_closer(self):
137        text = ("Plan.\n</think>\n\n<tool_call>\n<function=write_file>\n<parameter=path>\nout.txt\n</parameter>\n"
138                "<parameter=content>\nhello\n</parameter>\n</tool_call>")
139        self.every_route(text, [("write_file", {"path": "out.txt", "content": "hello"})])
140
141    def test_a_call_without_its_wrapper_closer_at_the_end(self):
142        text = "Plan.\n</think>\n\n" + call("write_file", path="out.txt", content="hello").removesuffix("\n</tool_call>")
143        self.every_route(text, [("write_file", {"path": "out.txt", "content": "hello"})])
144
145    def test_a_value_that_quotes_a_whole_call(self):
146        value = "first line\n" + call("write_file", path="nested.txt") + "\nlast line"
147        self.every_route("Plan.\n</think>\n\n" + call("write_file", path="fixture.txt", content=value),
148                         [("write_file", {"path": "fixture.txt", "content": value})])
149
150    def test_a_stray_closing_think_tag_keeps_the_call(self):
151        value = "reasoning sample:\n</think>\nanswer sample"
152        script = ("The content is\n```\n" + value + "\n```\nCall it.\n</think>\n\n" + call("write_file", path="out.txt", content=value))
153        got = self.read(script)
154        for (route, stream), (fin, calls, text) in got.items():
155            with self.subTest(route=route, stream=stream):
156                self.assertEqual(calls, [("write_file", {"path": "out.txt", "content": value})])
157                self.assertNotIn("</think>", text)
158
159
160if __name__ == "__main__":
161    unittest.main()