Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
server: include content key in final streaming delta when empty
Signed-off-by: Knight <2210620249@qq.com>
  • Loading branch information
Knight-XMUM committed Nov 22, 2026
commit da77717b55a9452b5b97c22e25f31fbf08e865f1
2 changes: 1 addition & 1 deletion mlx_lm/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1519,7 +1519,7 @@ def generate_response(
if self.object_type.startswith("chat.completion"):
key_name = "delta" if self.stream else "message"
choice[key_name] = {"role": "assistant"}
if not self.stream:
if not self.stream or finish_reason is not None:
# The schema requires "content" field to be present
choice[key_name]["content"] = text if text else None
elif text:
Expand Down
43 changes: 43 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1006,5 +1006,48 @@ def test_inflight_request_does_not_hang_after_thread_crash(self):
rg._await_response(Queue())




class TestGenerateResponseContent(unittest.TestCase):
def _make_handler(self, *, stream: bool):
handler = APIHandler.__new__(APIHandler)
handler.request_id = "chatcmpl-test"
handler.system_fingerprint = "fp-test"
handler.object_type = "chat.completion.chunk" if stream else "chat.completion"
handler.requested_model = "test-model"
handler.created = 0
handler.stream = stream
return handler

def test_streaming_final_chunk_includes_null_content_when_empty(self):
handler = self._make_handler(stream=True)
resp = handler.generate_response("", finish_reason="length")
delta = resp["choices"][0]["delta"]
self.assertIn("content", delta)
self.assertIsNone(delta["content"])
self.assertEqual(resp["choices"][0]["finish_reason"], "length")

def test_streaming_intermediate_reasoning_chunk_omits_empty_content(self):
handler = self._make_handler(stream=True)
resp = handler.generate_response("", finish_reason=None, reasoning_text="step 1")
delta = resp["choices"][0]["delta"]
self.assertNotIn("content", delta)
self.assertEqual(delta["reasoning"], "step 1")

def test_streaming_final_chunk_preserves_nonempty_content(self):
handler = self._make_handler(stream=True)
resp = handler.generate_response("hello", finish_reason="stop")
self.assertEqual(resp["choices"][0]["delta"]["content"], "hello")

def test_non_streaming_empty_content_is_none(self):
handler = self._make_handler(stream=False)
resp = handler.generate_response(
"", finish_reason="length", prompt_token_count=5, completion_token_count=10
)
msg = resp["choices"][0]["message"]
self.assertIn("content", msg)
self.assertIsNone(msg["content"])


if __name__ == "__main__":
unittest.main()