okami.mom/strata

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

Niko1221Functional-test fixes: agent tok/s and context, plain tool rows, Thinking Off proof, profile used, no download wording for installed models, plain chat, smaller agent prompt394de9291

main
11.9 KiB194 linesraw
1"""serve/test_effort_paths.py - every way a client sets the thinking level reaches the model's prompt (mock engine, no GPU).
2
3The level is nothing but a sentence in the rendered prompt (the template: xhigh / low sentences, none = the empty think
4block, medium = no sentence), so "the effort does not work" is always a request form whose level never reached the template.
5This pins the prompt each form produces, over the three APIs, the Chat settings shared with apps and the config's
6"reasoning_effort" (#1641).  0.1.44.1: the Responses API (/v1/responses, Codex) ignored the config's level.
7
8    python -m unittest serve.test_effort_paths -v
9"""
10from __future__ import annotations
11
12import json
13import sys
14import unittest
15import urllib.error
16import urllib.request
17from pathlib import Path
18
19sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
20from serve.frontend import ChatTemplate  # noqa: E402
21from serve.server import ByteTokenizer, MockEngine, Service, serve  # noqa: E402
22
23ROOT = Path(__file__).resolve().parents[1]
24MSG = [{"role": "user", "content": "hello"}]
25
26
27def level_of(prompt: str) -> str:
28    """What the template made of the level: xhigh and low have their sentence, none ends in the empty think block, and
29    medium is the prompt with no sentence at all (the model's own wording)."""
30    if prompt.rstrip().endswith("</think>"):
31        return "none"
32    if "Reasoning effort is set to low." in prompt:
33        return "low"
34    if "Reasoning effort is set to xhigh." in prompt:
35        return "xhigh"
36    return "medium"
37
38
39class EffortPaths(unittest.TestCase):
40    @classmethod
41    def setUpClass(cls):
42        cls.tok = ByteTokenizer()
43        cls.engine = MockEngine(cls.tok, "<think>\nhm\n</think>\n\nok", max_context=8192)
44        cls.svc = Service(cls.engine, cls.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
45        cls.httpd = serve(cls.svc, port=0)
46        cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
47
48    @classmethod
49    def tearDownClass(cls):
50        cls.httpd.shutdown()
51        cls.httpd.server_close()
52
53    def setUp(self):
54        self.svc.config_effort = None
55        self.svc.shared = {}
56
57    def post(self, path, body):
58        req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
59                                     headers={"Content-Type": "application/json"})
60        self.engine.last_prompt = []
61        try:
62            with urllib.request.urlopen(req, timeout=30) as r:
63                status = r.status
64                r.read()
65        except urllib.error.HTTPError as e:
66            with e:
67                status = e.code
68        return status
69
70    def level(self, path, body):
71        status = self.post(path, body)
72        self.assertEqual(status, 200, (path, body))
73        return level_of(self.tok.decode(self.engine.last_prompt))
74
75    # ---------------------------------------------------------------- the request's own level, every spelling
76    def test_openai_reasoning_effort(self):
77        for given, want in ((None, "xhigh"), ("none", "none"), ("off", "none"), ("minimal", "none"), ("low", "low"),
78                            ("medium", "medium"), ("high", "xhigh"), ("xhigh", "xhigh"), ("max", "xhigh"),
79                            ("LOW", "low"), (False, "none")):
80            body = {"messages": MSG, **({} if given is None else {"reasoning_effort": given})}
81            with self.subTest(given=given):
82                self.assertEqual(self.level("/v1/chat/completions", body), want)
83
84    def test_openai_reasoning_object_and_template_kwargs(self):
85        for given, want in (("low", "low"), ("medium", "medium"), ("high", "xhigh"), ("none", "none")):
86            with self.subTest(given=given):
87                self.assertEqual(self.level("/v1/chat/completions", {"messages": MSG, "reasoning": {"effort": given}}), want)
88                self.assertEqual(self.level("/v1/chat/completions",
89                                            {"messages": MSG, "chat_template_kwargs": {"reasoning_effort": given}}), want)
90        self.assertEqual(self.level("/v1/chat/completions",
91                                    {"messages": MSG, "chat_template_kwargs": {"enable_thinking": False}}), "none")
92
93    def test_an_unknown_level_is_a_400_not_the_default(self):
94        self.assertEqual(self.post("/v1/chat/completions", {"messages": MSG, "reasoning_effort": "huge"}), 400)
95
96    def test_anthropic_output_config_and_thinking(self):
97        for given, want in (("low", "low"), ("medium", "medium"), ("high", "xhigh")):
98            with self.subTest(effort=given):
99                self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50,
100                                                             "output_config": {"effort": given}}), want)
101        for budget, want in ((500, "low"), (2047, "low"), (2048, "medium"), (8191, "medium"), (8192, "xhigh"), (31999, "xhigh")):
102            with self.subTest(budget=budget):
103                self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50,
104                                                             "thinking": {"type": "enabled", "budget_tokens": budget}}), want)
105        self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50, "thinking": {"type": "disabled"}}),
106                         "none")
107        self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50}), "xhigh")   # nothing asked: it thinks
108
109    def test_responses_reasoning_effort(self):
110        for given, want in (("low", "low"), ("medium", "medium"), ("high", "xhigh"), ("none", "none"), ("minimal", "none")):
111            with self.subTest(given=given):
112                self.assertEqual(self.level("/v1/responses", {"input": "hello", "reasoning": {"effort": given}}), want)
113        self.assertEqual(self.level("/v1/responses", {"input": "hello"}), "xhigh")
114
115    # ---------------------------------------------------------------- the level of a request that names none
116    def test_config_level_reaches_every_api(self):
117        for cfg, want in (("low", "low"), ("medium", "medium"), ("high", "xhigh"), ("none", "none")):
118            self.svc.config_effort = cfg
119            with self.subTest(config=cfg):
120                self.assertEqual(self.level("/v1/chat/completions", {"messages": MSG}), want)
121                self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50}), want)
122                self.assertEqual(self.level("/v1/responses", {"input": "hello"}), want)      # 0.1.44.1: it ignored the config
123
124    def test_the_requests_own_level_beats_the_config(self):
125        self.svc.config_effort = "low"
126        self.assertEqual(self.level("/v1/chat/completions", {"messages": MSG, "reasoning_effort": "high"}), "xhigh")
127        self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50, "output_config": {"effort": "high"}}),
128                         "xhigh")
129        self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50,
130                                                     "thinking": {"type": "enabled", "budget_tokens": 20000}}), "xhigh")
131        self.assertEqual(self.level("/v1/responses", {"input": "hello", "reasoning": {"effort": "high"}}), "xhigh")
132        self.assertEqual(self.level("/v1/chat/completions", {"messages": MSG, "reasoning_effort": "none"}), "none")
133        self.assertEqual(self.level("/v1/chat/completions", {"messages": MSG, "reasoning_effort": False}), "none")
134
135    def test_the_chat_settings_shared_with_apps_beat_the_config(self):
136        self.svc.config_effort = "low"
137        self.svc.shared = {"reasoning_effort": "high"}
138        for path, body in (("/v1/chat/completions", {"messages": MSG}), ("/v1/messages", {"messages": MSG, "max_tokens": 50}),
139                           ("/v1/responses", {"input": "hello"})):
140            with self.subTest(path=path):
141                self.assertEqual(self.level(path, body), "xhigh")
142        self.svc.shared = {"reasoning_effort": "none"}
143        for path, body in (("/v1/chat/completions", {"messages": MSG}), ("/v1/messages", {"messages": MSG, "max_tokens": 50}),
144                           ("/v1/responses", {"input": "hello"})):
145            with self.subTest(path=path, shared="none"):
146                self.assertEqual(self.level(path, body), "none")
147
148    def test_the_web_apps_request_shape(self):
149        # serve/web/app.js: {model, messages, stream, reasoning_effort: settings.thinking} with none / low / medium / high
150        for given, want in (("none", "none"), ("low", "low"), ("medium", "medium"), ("high", "xhigh")):
151            with self.subTest(given=given):
152                self.assertEqual(self.level("/v1/chat/completions", {"model": "m", "messages": MSG, "stream": True,
153                                                                     "temperature": 0.6, "top_p": 0.95, "top_k": 20,
154                                                                     "reasoning_effort": given}), want)
155
156    def test_tools_and_a_system_message_keep_the_level(self):
157        tools = [{"type": "function", "function": {"name": "f", "description": "d",
158                                                    "parameters": {"type": "object", "properties": {}}}}]
159        body = {"messages": [{"role": "system", "content": "be brief"}] + MSG, "tools": tools}
160        self.assertEqual(self.level("/v1/chat/completions", {**body, "reasoning_effort": "low"}), "low")
161        self.assertEqual(self.level("/v1/chat/completions", {**body, "reasoning_effort": "high"}), "xhigh")
162        self.assertEqual(self.level("/v1/chat/completions", {**body, "reasoning_effort": "none"}), "none")
163
164    def test_the_level_follows_a_conversation(self):
165        history = MSG + [{"role": "assistant", "content": "hi", "reasoning_content": "greet"},
166                         {"role": "user", "content": "and now?"}]
167        for given, want in (("low", "low"), ("medium", "medium"), ("none", "none")):
168            with self.subTest(given=given):
169                self.assertEqual(self.level("/v1/chat/completions", {"messages": history, "reasoning_effort": given}), want)
170
171
172    def test_the_agents_request_shape_with_thinking_off(self):
173        """The app's agent (Harness) sends no reasoning_effort when Thinking is Off, only chat_template_kwargs {enable_thinking: false}, with tools, a
174        system message, earlier reasoning and a token cap. That one flag must reach the template as the empty think block, whatever else is in the
175        request or configured (a thinking model that went on reasoning with the menu on Off was this request form).  The same body with
176        enable_thinking true / an effort keeps thinking."""
177        tools = [{"type": "function", "function": {"name": "pwsh", "description": "d", "parameters": {"type": "object", "properties": {}}}}]
178        history = [{"role": "developer", "content": "You are a helpful assistant."}, {"role": "user", "content": "first"},
179                   {"role": "assistant", "content": "ok", "reasoning_content": "earlier thoughts"}, {"role": "user", "content": "now?"}]
180        agent = {"model": "m", "messages": history, "tools": tools, "stream": True, "stream_options": {"include_usage": True},
181                 "max_completion_tokens": 4096}
182        for config in (None, "high", "low"):
183            self.svc.config_effort = config
184            with self.subTest(config=config):
185                self.assertEqual(self.level("/v1/chat/completions", {**agent, "chat_template_kwargs": {"enable_thinking": False}}), "none")
186        self.svc.config_effort = None
187        self.assertEqual(self.level("/v1/chat/completions", {**agent, "chat_template_kwargs": {"enable_thinking": True, "reasoning_effort": "low"}}), "low")
188        self.assertEqual(self.level("/v1/chat/completions", {**agent, "chat_template_kwargs": {"enable_thinking": True, "reasoning_effort": "high"}}), "xhigh")
189        # the same flag in the plain (no tools) body the direct chat sends alongside a budget
190        self.assertEqual(self.level("/v1/chat/completions", {"messages": MSG, "chat_template_kwargs": {"enable_thinking": False}, "reasoning_effort": "none"}), "none")
191
192
193if __name__ == "__main__":
194    unittest.main()