diff --git a/serve/frontend.py b/serve/frontend.py index 9e73ae0a..07e369d0 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -143,10 +143,27 @@ def _late_system_to_user(messages: list[dict]) -> list[dict]: return [dict(m, role="user") if m.get("role") == "system" and i > 0 else m for i, m in enumerate(messages)] +def _object_list(value, name: str) -> list[dict]: + """#460: a request's "messages" (or a message's "tool_calls") as a list of objects. Some clients send the array + double-encoded, as a JSON string, which used to be iterated character by character and crashed on m.get: such a + string is decoded. Anything that is still not a list of objects is a ValueError, which the server answers with + a 400 naming the field. None (or no field) is an empty list, as a missing field always was.""" + if value is None: + return [] + if isinstance(value, str): + try: + value = json.loads(value) + except ValueError: + raise ValueError(f"{name} must be a list of objects (a string was sent that is not JSON)") from None + if not isinstance(value, list) or not all(isinstance(m, dict) for m in value): + raise ValueError(f"{name} must be a list of objects") + return value + + def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] - for m in req.get("messages", []): + for m in _object_list(req.get("messages"), "messages"): role = m.get("role") if role == "developer": role = "system" @@ -155,8 +172,10 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: out["reasoning_content"] = m["reasoning_content"] if m.get("tool_calls"): calls = [] - for c in m["tool_calls"]: + for c in _object_list(m["tool_calls"], "tool_calls"): fn = c.get("function", c) + if not isinstance(fn, dict): + raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)") args = fn.get("arguments") if isinstance(args, str): # the template requires a mapping, not a JSON string args = json.loads(args) if args.strip() else {} @@ -186,7 +205,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d system = req.get("system") if system: messages.append({"role": "system", "content": _text_of(system)}) - for m in req.get("messages", []): + for m in _object_list(req.get("messages"), "messages"): content = m.get("content") if isinstance(content, str): messages.append({"role": m["role"], "content": content}) diff --git a/serve/test_server.py b/serve/test_server.py index 6869de7a..ad2e9831 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -474,6 +474,18 @@ class ClientShapes(unittest.TestCase): "messages": [{"role": "user", "content": "hi"}]}) self.assertEqual(status, 200, b) # the server goes on + def test_messages_as_a_json_string_over_http(self): + # #460: a double-encoded "messages" is answered; one that is not a list of objects is a 400, not a 500 + encoded = json.dumps([{"role": "user", "content": "1+1?"}]) + for path in ("/v1/chat/completions", "/v1/messages"): + with self.subTest(path=path): + status, b = self.post(path, {"model": "x", "max_tokens": 20, "messages": encoded}) + self.assertEqual(status, 200, b) + self.assertIn("1+1?", self.prompt_text()) + status, b = self.post(path, {"model": "x", "max_tokens": 20, "messages": ["hi"]}) + self.assertEqual(status, 400, b) + self.assertIn("messages must be a list of objects", b["error"]["message"]) + def test_vision_temp_image_removed_when_the_pipe_fails(self): # #352: the temporary image goes even when the encoder's pipe raises from serve.server import Vision @@ -499,6 +511,32 @@ class ClientShapes(unittest.TestCase): msgs, _, _ = anthropic_to_messages({"system": "S", "messages": [{"role": "user", "content": "u"}]}) self.assertEqual([m["role"] for m in msgs], ["system", "user"]) + def test_messages_sent_as_a_json_string(self): + # #460: a client that double-encodes "messages" (and "tool_calls") as a JSON string gets them decoded; what is + # still not a list of objects is a ValueError (the server's 400), not an AttributeError on m.get + from serve.frontend import anthropic_to_messages, openai_to_messages + call = [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{\"x\": 1}"}}] + listed = [{"role": "user", "content": "u"}, {"role": "assistant", "content": "", "tool_calls": call}] + encoded = [listed[0], dict(listed[1], tool_calls=json.dumps(call))] + want = openai_to_messages({"messages": listed})[0] + self.assertEqual(want[1]["tool_calls"], [{"function": {"name": "f", "arguments": {"x": 1}}}]) + self.assertEqual(openai_to_messages({"messages": json.dumps(listed)})[0], want) + self.assertEqual(openai_to_messages({"messages": json.dumps(encoded)})[0], want) + anth = [{"role": "user", "content": "u"}] + self.assertEqual(anthropic_to_messages({"messages": json.dumps(anth)})[0], + anthropic_to_messages({"messages": anth})[0]) + self.assertEqual(openai_to_messages({})[0], []) # no field: nothing, as before + self.assertEqual(openai_to_messages({"messages": None})[0], []) + for bad in ("not json", "\"a string\"", json.dumps({"role": "user"}), ["hi"], [{"role": "user"}, 3], 5, + {"role": "user", "content": "u"}): + for fn in (openai_to_messages, anthropic_to_messages): + with self.subTest(bad=bad, fn=fn.__name__): + with self.assertRaisesRegex(ValueError, "messages must be a list of objects"): + fn({"messages": bad}) + for calls in (["f"], "[1]", [{"function": "f"}], "{"): + with self.subTest(calls=calls), self.assertRaisesRegex(ValueError, "tool_calls must be a list of objects"): + openai_to_messages({"messages": [{"role": "assistant", "content": "", "tool_calls": calls}]}) + class SamplingKeys(unittest.TestCase): """The GEN line's sampling keys: top_k 0 ("off") or wider than the engine's 64 get the widest list, 64 (they used