Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(server): send a queued native prompt to a chat-only upstream as one user turn (#871)

Krisztian Gajdarb8c557b9144d
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index ac46e9884..31ce14067 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -6562,6 +6562,7 @@ impl ChatRequestParams {
best_of: self.best_of,
stream: self.stream,
lora_adapter: self.lora_adapter.clone(),
+ native_prompt: None,
}),
routing_key: self.routing_key,
prompt_cache_key: self.prompt_cache_key,
@@ -14252,6 +14253,7 @@ fn generate_params_from_json(
stream,
lora_adapter,
include_reasoning: None,
+ native_prompt: Some(true),
}))
}
@@ -14684,6 +14686,7 @@ fn generate_params_from_rmpv(
stream,
lora_adapter,
include_reasoning: None,
+ native_prompt: Some(true),
}))
}
@@ -21186,6 +21189,32 @@ mod tests {
assert!(generate_params_have_images(&params));
}
+ #[test]
+ fn test_only_the_native_route_marks_its_prompt_native() {
+ let body = serde_json::json!({"prompt": "Read", "max_new_tokens": 8});
+ assert_eq!(_expect_generate_ok(&body).native_prompt, Some(true));
+ let rmpv::Value::Map(map) = json_to_rmpv(body) else {
+ panic!("object must map")
+ };
+ let params = generate_params_from_rmpv(&map)
+ .expect("valid request")
+ .expect("generate params");
+ assert_eq!(params.native_prompt, Some(true));
+ let Ok((_, completions)) = completions_dispatch_inputs(&_completions_body_min("m")) else {
+ panic!("valid completions body")
+ };
+ assert_eq!(
+ completions.generate.expect("generate params").native_prompt,
+ None
+ );
+ let chat =
+ serde_json::json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]});
+ let Ok((_, chat)) = chat_completions_dispatch_inputs(&chat) else {
+ panic!("valid chat body")
+ };
+ assert_eq!(chat.generate.expect("generate params").native_prompt, None);
+ }
+
#[test]
fn test_generate_native_image_validation_has_json_msgpack_parity() {
let body = serde_json::json!({
diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rs
index 0726042c6..d9db414ff 100644
--- a/packages/sie_gateway/src/queue/publisher.rs
+++ b/packages/sie_gateway/src/queue/publisher.rs
@@ -446,6 +446,12 @@ pub struct GenerateParams {
/// private.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub include_reasoning: Option<bool>,
+ /// ``Some(true)`` only from the native ``/v1/generate`` route. A
+ /// remote-backed model whose upstream serves chat only then receives
+ /// the prompt as one user message. Every other route's prompt is a raw
+ /// continuation, which such an upstream refuses.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub native_prompt: Option<bool>,
/// Caller-supplied routing affinity hint. Highest-priority input
/// to the HRW key resolution in `crate::routing::key`.
#[serde(default, skip_serializing_if = "Option::is_none")]
diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index 3e478fa5c..652321178 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -36,6 +36,7 @@ import json
import logging
import math
import os
+import re
import sys
import time
import uuid
@@ -141,6 +142,9 @@ _GRAMMAR_EXECUTOR = ThreadPoolExecutor(max_workers=4, thread_name_prefix="gramma
# until ack_wait (which would trigger a JetStream redelivery storm).
_GRAMMAR_FOLLOWER_TIMEOUT_S = 30.0
+# OpenAI's ``response_format.json_schema.name`` contract.
+_UPSTREAM_SCHEMA_NAME = re.compile(r"[A-Za-z0-9_-]{1,64}")
+
# SGLang owns request-time grammar compilation.
#
# By default the worker forwards the raw schema/regex/EBNF straight to
@@ -828,6 +832,10 @@ class _GenerateRequestParams:
# ``reasoning_delta`` chunks instead of dropping it. Honoured only for a
# model whose config declares reasoning.
include_reasoning: bool = False
+ # Set only by the native ``/v1/generate`` route: a remote-backed model on
+ # a chat-only upstream receives the prompt as one user message. Other
+ # routes' prompts are raw continuations.
+ native_prompt: bool = False
def _remote_chat_content(message: _ChatMessage, index: int) -> list[dict[str, Any]]:
@@ -922,7 +930,8 @@ def _remote_chat_parameters(
body["tool_choice"] = params.tool_choice
if params.grammar is not None:
grammar = params.grammar
- schema: dict[str, Any] = {"name": grammar.label or "response", "schema": grammar.value}
+ name = grammar.label if grammar.label and _UPSTREAM_SCHEMA_NAME.fullmatch(grammar.label) else "response"
+ schema: dict[str, Any] = {"name": name, "schema": grammar.value}
if grammar.strict is not None:
schema["strict"] = grammar.strict
body["response_format"] = {"type": "json_schema", "json_schema": schema}
@@ -1922,6 +1931,20 @@ class StreamingProcessor:
)
return
params = validation
+ # A remote-backed model has no local template and a chat-only upstream
+ # has no raw endpoint, so a native prompt is sent as one user turn, the
+ # shape the gateway already gives a native prompt that carries images.
+ if (
+ params.native_prompt
+ and isinstance(params.input, _PromptInput)
+ and config is not None
+ and config.remote_backed
+ and isinstance(adapter, OpenAIUpstreamAdapter)
+ and not adapter.supports_raw_completions
+ ):
+ params = replace(
+ params, input=_MessagesInput(messages=(_ChatMessage(role="user", content=params.input.prompt),))
+ )
if params.lora_adapter is not None and adapter.lora_capability() is not None:
try:
ready, _ = await self._registry.ensure_lora_loaded_async(model_id, params.lora_adapter)
@@ -3661,6 +3684,9 @@ class StreamingProcessor:
if include_reasoning_raw is not None and not isinstance(include_reasoning_raw, bool):
return _ValidationError(code="invalid_request", message="'include_reasoning' must be a boolean")
include_reasoning = bool(include_reasoning_raw)
+ native_prompt_raw = params.get("native_prompt")
+ if native_prompt_raw is not None and not isinstance(native_prompt_raw, bool):
+ return _ValidationError(code="invalid_request", message="'native_prompt' must be a boolean")
# OpenAI ``seed`` / ``logit_bias`` / ``logprobs`` / ``top_logprobs``
# round-trips. Gateway is the authority for shape validation
@@ -3808,6 +3834,7 @@ class StreamingProcessor:
stream=stream,
lora_adapter=lora_adapter,
include_reasoning=include_reasoning,
+ native_prompt=bool(native_prompt_raw),
)
async def _get_tokenizer(self, model_id: str) -> TokenizerLike:
diff --git a/packages/sie_server/tests/processors/test_remote_chat.py b/packages/sie_server/tests/processors/test_remote_chat.py
index 805c58459..24aa323fa 100644
--- a/packages/sie_server/tests/processors/test_remote_chat.py
+++ b/packages/sie_server/tests/processors/test_remote_chat.py
@@ -303,6 +303,52 @@ async def test_regex_refuses_without_dispatch(remote: tuple) -> None:
assert remote[3] == []
[email protected]("remote", ["openai"], indirect=True)
+ ("grammar", "name"),
+ [
+ (None, None),
+ ({"kind": "json_schema", "value": {"type": "object"}, "label": "result-v1_2"}, "result-v1_2"),
+ ({"kind": "json_schema", "value": {"type": "object"}, "label": "customer result"}, "response"),
+ ({"kind": "json_schema", "value": {"type": "object"}, "label": "x" * 65}, "response"),
+ ],
+)
+async def test_native_prompt_on_a_chat_only_upstream_is_one_user_turn(
+ remote: tuple, grammar: dict | None, name: str | None
+) -> None:
+ answer = '{"answer": "yes"}'
+ respond(remote, frames=[choice(answer), choice("", finish="stop"), {"choices": [], "usage": USAGE}, "[DONE]"])
+ msg, chunks = await run(remote, prompt="question", native_prompt=True, **({"grammar": grammar} if grammar else {}))
+ assert "".join(chunk.get("text_delta", "") for chunk in chunks) == answer
+ assert chunks[-1]["finish_reason"] == "stop"
+ assert chunks[-1]["usage"] == USAGE
+ assert len(remote[3]) == 1
+ assert remote[3][0].url.path.endswith("/chat/completions")
+ body = json.loads(remote[3][0].content)
+ assert body["messages"] == [{"role": "user", "content": "question"}]
+ assert "prompt" not in body
+ if grammar:
+ assert body["response_format"] == {
+ "type": "json_schema",
+ "json_schema": {"name": name, "schema": {"type": "object"}},
+ }
+ else:
+ assert "response_format" not in body
+ msg.ack.assert_awaited_once()
+
+
[email protected]("remote", ["openai"], indirect=True)
+async def test_raw_prompt_on_a_chat_only_upstream_is_refused_without_dispatch(
+ remote: tuple, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(remote[1], "_check_context_length", AsyncMock(return_value=None))
+ respond(remote)
+ msg, chunks = await run(remote, prompt="Once upon a time")
+ assert chunks[-1]["error"]["code"] == "unsupported_field"
+ assert remote[3] == []
+ msg.ack.assert_awaited_once()
+
+
async def test_tool_fragments_and_required_choice_preserved(remote: tuple) -> None:
frames = [
{