Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(serve): wire logits processors and reasoning parser into streaming responses (#1448) (#1607)

Nariman Abdikarim51c1135fdee4
diff --git a/changelog.d/0.75.1/1607.fixed.md b/changelog.d/0.75.1/1607.fixed.md
new file mode 100644
index 00000000..3b53a9c0
--- /dev/null
+++ b/changelog.d/0.75.1/1607.fixed.md
@@ -0,0 +1 @@
+- `soup serve`: wire output constraint logits processors and reasoning parser into `_stream_response` so streaming chat completions (`stream: true`) apply structured generation constraints and strip `<think>` blocks before emitting SSE events (part of #1448 by @Nari-Ab in #1607).
diff --git a/src/soup_cli/commands/serve.py b/src/soup_cli/commands/serve.py
index bfecd647..2392c9af 100644
--- a/src/soup_cli/commands/serve.py
+++ b/src/soup_cli/commands/serve.py
@@ -1974,6 +1974,12 @@ def _create_app(
if request.stream:
stream_started = time.perf_counter()
+ from soup_cli.utils.structured_output import (
+ build_logits_processors,
+ )
+ processors = build_logits_processors(
+ output_constraint, tokenizer,
+ )
return StreamingResponse(
_stream_response(
model_obj, tokenizer, messages,
@@ -1997,6 +2003,9 @@ def _create_app(
canary_outcome=(
lambda ok: _record_canary_outcome(canary_tracking, ok)
),
+ logits_processor=processors or None,
+ ngram_config=ngram_config,
+ reasoning_parser=reasoning_parser,
),
media_type="text/event-stream",
)
@@ -2504,6 +2513,9 @@ def _stream_response(
adapter_lock=None, adapter_names=None,
requested_adapter=None, active_adapter=None,
canary_outcome=None,
+ logits_processor=None,
+ ngram_config=None,
+ reasoning_parser=None,
):
"""Generator that yields SSE chunks for streaming responses."""
chat_id = f"chatcmpl-{uuid.uuid4().hex[:8]}"
@@ -2545,6 +2557,8 @@ def _stream_response(
assistant_model=assistant_model,
assistant_tokenizer=assistant_tokenizer,
num_assistant_tokens=num_assistant_tokens,
+ logits_processor=logits_processor,
+ ngram_config=ngram_config,
kv_cache_generate_kwargs=kv_cache_generate_kwargs,
)
except Exception:
@@ -2557,6 +2571,14 @@ def _stream_response(
if canary_outcome is not None:
canary_outcome(True)
+ # Strip reasoning blocks if configured
+ if reasoning_parser is not None:
+ from soup_cli.utils.reasoning_parser import strip_reasoning
+
+ response_text = strip_reasoning(
+ response_text, reasoning_parser,
+ )
+
# Simulate streaming by sending word-by-word
words = response_text.split(" ")
for idx, word in enumerate(words):
diff --git a/tests/test_issue1448_serve_streaming.py b/tests/test_issue1448_serve_streaming.py
new file mode 100644
index 00000000..b38b302c
--- /dev/null
+++ b/tests/test_issue1448_serve_streaming.py
@@ -0,0 +1,141 @@
+"""Tests for issue #1448: soup serve streaming ignores structured-output and reasoning-parser.
+
+Acceptance criteria:
+- Streaming SSE of a <think> reply contains no <think> when reasoning_parser is configured.
+- The output constraint (logits processor) reaches generation on the streaming path.
+"""
+
+from __future__ import annotations
+
+import json
+from unittest import mock
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastapi.testclient import TestClient
+
+import soup_cli.commands.serve as serve
+from soup_cli.commands.serve import _create_app
+from soup_cli.utils import structured_output
+
+
+def _make_app(**kwargs):
+ model = MagicMock()
+ tokenizer = MagicMock()
+ tokenizer.pad_token_id = 0
+ defaults = dict(
+ model_obj=model,
+ tokenizer=tokenizer,
+ device="cpu",
+ model_name="test-model",
+ max_tokens_default=64,
+ )
+ defaults.update(kwargs)
+ return _create_app(**defaults)
+
+
+def test_streaming_sse_strips_reasoning():
+ """Streaming SSE chunks must not contain <think> blocks when reasoning_parser is active."""
+ app = _make_app(reasoning_parser="deepseek-r1")
+ client = TestClient(app)
+
+ raw_reply = "<think>internal reasoning steps</think>Hello world!"
+ with patch(
+ "soup_cli.commands.serve._generate_response",
+ return_value=(raw_reply, 4, 10),
+ ):
+ response = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "test-model",
+ "messages": [{"role": "user", "content": "hi"}],
+ "stream": True,
+ },
+ )
+
+ assert response.status_code == 200
+ body = response.text
+ assert "<think>" not in body
+ assert "internal reasoning steps" not in body
+ assert "Hello" in body
+ assert "world!" in body
+
+
+def test_streaming_forwards_logits_processors():
+ """Streaming chat completions must pass built logits processors to generation."""
+ dummy_processor = MagicMock()
+ app = _make_app(output_constraint={"type": "json_schema", "schema": "{}"})
+ client = TestClient(app)
+
+ with (
+ patch(
+ "soup_cli.utils.structured_output.build_logits_processors",
+ return_value=[dummy_processor],
+ ),
+ patch(
+ "soup_cli.commands.serve._generate_response",
+ return_value=("output", 2, 5),
+ ) as mock_generate,
+ ):
+ response = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "test-model",
+ "messages": [{"role": "user", "content": "hi"}],
+ "stream": True,
+ },
+ )
+
+ assert response.status_code == 200
+ mock_generate.assert_called_once()
+ _, kwargs = mock_generate.call_args
+ assert kwargs.get("logits_processor") == [dummy_processor]
+
+
+REGEX = {"kind": "regex", "pattern": "a+"}
+
+
+def _sse_text(body: str) -> str:
+ return "".join(
+ json.loads(line[len("data: "):])["choices"][0]["delta"].get("content", "")
+ for line in body.splitlines()
+ if line.startswith("data: {") and '"choices"' in line
+ )
+
+
+ "parser, raw, visible",
+ [
+ ("deepseek-r1", "<think>plan</think>aaa and more", "aaa and more"),
+ ("openthinker", "<|begin_of_thought|>t<|end_of_thought|>aaa", "aaa"),
+ (None, "<think>kept</think>aaa", "<think>kept</think>aaa"),
+ ],
+)
+def test_streaming_matches_non_streaming(parser, raw, visible):
+ seen, built_for = [], []
+
+ def fake_generate(model, tokenizer, messages, **kwargs):
+ seen.append((kwargs.get("logits_processor"), kwargs.get("ngram_config")))
+ return (raw, 3, 2)
+
+ def fake_build(constraint, tokenizer):
+ built_for.append(constraint)
+ return ["processor-for", constraint]
+
+ ngram = object()
+ with mock.patch.object(serve, "_generate_response", fake_generate), \
+ mock.patch.object(structured_output, "build_logits_processors", fake_build):
+ client = TestClient(serve._create_app(
+ model_obj=object(), tokenizer=object(), device="cpu", model_name="m",
+ max_tokens_default=8, output_constraint=REGEX, reasoning_parser=parser,
+ ngram_config=ngram,
+ ))
+ body = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}
+ plain = client.post("/v1/chat/completions", json=body)
+ streamed = client.post("/v1/chat/completions", json={**body, "stream": True})
+
+ assert plain.status_code == streamed.status_code == 200
+ assert plain.json()["choices"][0]["message"]["content"] == visible
+ assert _sse_text(streamed.text) == visible
+ assert built_for == [REGEX, REGEX]
+ assert seen[0] == seen[1] == (["processor-for", REGEX], ngram)