okami.mom/strata

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

waveringanaserve tests: bring back the DeepSeek V4.1 cases upstream cut with the enginecded60248

main
6.9 KiB155 linesraw
1"""Anthropic tool_result blocks must follow tool_use_id before the template drops it."""
2import copy
3import http.client
4import json
5from pathlib import Path
6import unittest
7
8from serve.frontend import ChatTemplate, anthropic_to_messages
9from serve.server import ByteTokenizer, MockEngine, Service, serve
10
11
12TEMPLATE = ChatTemplate(Path(__file__).with_name("chat_template.jinja"))
13DEEPSEEK = ChatTemplate(Path(__file__).with_name("fixtures") / "deepseek41" / "chat_template.jinja")
14
15
16def history():
17    """Two calls of one tool, answered in the order they finished: what Claude Code 2.1.316 sends for parallel Greps."""
18    return [
19        {"role": "user", "content": "Search for both."},
20        {"role": "assistant", "content": [
21            {"type": "tool_use", "id": "toolu_slow", "name": "Grep", "input": {"pattern": "slow"}},
22            {"type": "tool_use", "id": "toolu_fast", "name": "Grep", "input": {"pattern": "fast"}}]},
23        {"role": "user", "content": [
24            {"type": "tool_result", "tool_use_id": "toolu_fast", "content": "RESULT_FROM_FAST"},
25            {"type": "tool_result", "tool_use_id": "toolu_slow", "content": "RESULT_FROM_SLOW"}]},
26    ]
27
28
29def in_call_order():
30    raw = history()
31    raw[2]["content"].reverse()
32    return raw
33
34
35def normalized(messages):
36    return anthropic_to_messages({"messages": messages})[0]
37
38
39def results(messages):
40    return [m["content"] for m in normalized(messages) if m["role"] == "tool"]
41
42
43class AnthropicToolResults(unittest.TestCase):
44    def test_reversed_results_of_the_same_tool_follow_tool_use_id(self):
45        raw = history()
46        before = copy.deepcopy(raw)
47        self.assertEqual(results(raw), ["RESULT_FROM_SLOW", "RESULT_FROM_FAST"])
48        self.assertEqual(raw, before)
49        for template in (TEMPLATE, DEEPSEEK):
50            with self.subTest(template=str(template)):
51                prompt = template.render(normalized(raw), enable_thinking=False)
52                self.assertEqual(prompt, template.render(normalized(in_call_order()), enable_thinking=False))
53                self.assertLess(prompt.index("RESULT_FROM_SLOW"), prompt.index("RESULT_FROM_FAST"))
54
55    def test_already_ordered_and_legacy_prompts_are_identical(self):
56        ordered = in_call_order()
57        legacy = copy.deepcopy(ordered)
58        for block in legacy[1]["content"]:
59            block.pop("id")
60        for block in legacy[2]["content"]:
61            block.pop("tool_use_id")
62        self.assertEqual(normalized(ordered), normalized(legacy))
63        self.assertEqual([m["content"] for m in normalized(ordered)[2:]], ["RESULT_FROM_SLOW", "RESULT_FROM_FAST"])
64
65    def test_ids_never_reach_the_template(self):
66        for raw in (history(), in_call_order()):
67            messages = normalized(raw)
68            self.assertTrue(all(set(m) == {"role", "content"} for m in messages[2:]))
69            self.assertTrue(all(set(c) == {"function"} for c in messages[1]["tool_calls"]))
70
71    def test_ambiguous_or_incomplete_ids_preserve_received_order(self):
72        for case in ("missing_call", "missing_result", "duplicate_call", "duplicate_result", "unknown",
73                     "list_call", "list_result", "empty_call", "empty_result", "partial"):
74            raw = history()
75            calls, blocks = raw[1]["content"], raw[2]["content"]
76            if case == "missing_call":
77                calls[0].pop("id")
78            elif case == "missing_result":
79                blocks[0].pop("tool_use_id")
80            elif case == "duplicate_call":
81                calls[1]["id"] = "toolu_slow"
82            elif case == "duplicate_result":
83                blocks[1]["tool_use_id"] = "toolu_fast"
84            elif case == "unknown":
85                blocks[0]["tool_use_id"] = "unknown"
86            elif case == "list_call":
87                calls[0]["id"] = []
88            elif case == "list_result":
89                blocks[0]["tool_use_id"] = []
90            elif case == "empty_call":
91                calls[0]["id"] = ""
92            elif case == "empty_result":
93                blocks[0]["tool_use_id"] = ""
94            else:
95                blocks.pop()
96            with self.subTest(case=case):
97                self.assertEqual(results(raw), [b["content"] for b in blocks])
98
99    def test_each_tool_run_is_scoped_to_its_assistant_turn(self):
100        self.assertEqual(results(history() + history()), ["RESULT_FROM_SLOW", "RESULT_FROM_FAST"] * 2)
101
102    def test_results_split_across_user_messages_are_one_run(self):
103        raw = history()
104        first, second = raw[2]["content"]
105        raw[2:] = [{"role": "user", "content": [first]}, {"role": "user", "content": [second]}]
106        self.assertEqual(results(raw), ["RESULT_FROM_SLOW", "RESULT_FROM_FAST"])
107
108    def test_system_message_between_calls_and_results_keeps_received_order(self):
109        raw = history()
110        raw.insert(2, {"role": "system", "content": "late note"})
111        self.assertEqual(results(raw), ["RESULT_FROM_FAST", "RESULT_FROM_SLOW"])
112
113    def test_text_beside_the_results_stays_after_them(self):
114        raw = history()
115        raw[2]["content"].append({"type": "text", "text": "and then?"})
116        self.assertEqual([(m["role"], m["content"]) for m in normalized(raw)[2:]],
117                         [("tool", "RESULT_FROM_SLOW"), ("tool", "RESULT_FROM_FAST"), ("user", "and then?")])
118
119    def test_multimodal_result_moves_with_its_call(self):
120        raw = history()
121        image = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AA=="}}
122        raw[2]["content"][0]["content"] = [{"type": "text", "text": "RESULT_FROM_FAST"}, image]
123        got = results(raw)
124        self.assertEqual(got[0], "RESULT_FROM_SLOW")
125        self.assertEqual([p.get("type") for p in got[1]], ["text", "image"])
126
127    def test_http_engine_receives_the_ordered_prompt(self):
128        tok = ByteTokenizer()
129        engine = MockEngine(tok, "ok", max_context=4096)
130        service = Service(engine, tok, TEMPLATE)
131        httpd = serve(service, port=0)
132        try:
133            for stream in (False, True):
134                with self.subTest(stream=stream):
135                    engine.last_prompt = None
136                    connection = http.client.HTTPConnection("127.0.0.1", httpd.server_address[1], timeout=10)
137                    try:
138                        connection.request("POST", "/v1/messages", json.dumps({
139                            "model": "x", "messages": history(), "max_tokens": 16, "stream": stream,
140                            "thinking": {"type": "disabled"}}), {"Content-Type": "application/json"})
141                        response = connection.getresponse()
142                        body = response.read()
143                    finally:
144                        connection.close()
145                    self.assertEqual(response.status, 200, body)
146                    prompt = tok.decode(engine.last_prompt)
147                    self.assertLess(prompt.index("RESULT_FROM_SLOW"), prompt.index("RESULT_FROM_FAST"))
148        finally:
149            httpd.shutdown()
150            httpd.server_close()
151
152
153
154if __name__ == "__main__":
155    unittest.main()