Files
sglang/test/registered/unit/entrypoints/openai/test_protocol.py
T

713 lines
28 KiB
Python

# Copyright 2023-2024 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for OpenAI API protocol models"""
import unittest
from typing import List, Optional
from pydantic import BaseModel, Field, ValidationError
from sglang.srt.entrypoints.openai.protocol import (
ChatCompletionMessageContentImageURL,
ChatCompletionRequest,
ChatCompletionResponse,
ChatCompletionResponseChoice,
ChatMessage,
CompletionRequest,
Function,
ModelCard,
ModelList,
Tool,
UsageInfo,
)
from sglang.test.ci.ci_register import register_cpu_ci
register_cpu_ci(est_time=7, suite="base-a-test-cpu")
class TestModelCard(unittest.TestCase):
"""Test ModelCard protocol model"""
def test_model_card_serialization(self):
"""Test model card JSON serialization"""
card = ModelCard(id="test-model", max_model_len=4096)
data = card.model_dump()
self.assertEqual(data["id"], "test-model")
self.assertEqual(data["object"], "model")
self.assertEqual(data["max_model_len"], 4096)
class TestModelList(unittest.TestCase):
"""Test ModelList protocol model"""
def test_empty_model_list(self):
"""Test empty model list creation"""
model_list = ModelList()
self.assertEqual(model_list.object, "list")
self.assertEqual(len(model_list.data), 0)
def test_model_list_with_cards(self):
"""Test model list with model cards"""
cards = [
ModelCard(id="model-1"),
ModelCard(id="model-2", max_model_len=2048),
]
model_list = ModelList(data=cards)
self.assertEqual(len(model_list.data), 2)
self.assertEqual(model_list.data[0].id, "model-1")
self.assertEqual(model_list.data[1].id, "model-2")
class TestCompletionRequest(unittest.TestCase):
"""Test CompletionRequest protocol model"""
def test_basic_completion_request(self):
"""Test basic completion request"""
request = CompletionRequest(model="test-model", prompt="Hello world")
self.assertEqual(request.model, "test-model")
self.assertEqual(request.prompt, "Hello world")
self.assertEqual(request.max_tokens, 16) # default
self.assertEqual(request.temperature, 1.0) # default
self.assertEqual(request.n, 1) # default
self.assertFalse(request.stream) # default
self.assertFalse(request.echo) # default
def test_completion_request_sglang_extensions(self):
"""Test completion request with SGLang-specific extensions"""
request = CompletionRequest(
model="test-model",
prompt="Hello",
top_k=50,
min_p=0.1,
repetition_penalty=1.1,
regex=r"\d+",
json_schema='{"type": "object"}',
lora_path="/path/to/lora",
)
self.assertEqual(request.top_k, 50)
self.assertEqual(request.min_p, 0.1)
self.assertEqual(request.repetition_penalty, 1.1)
self.assertEqual(request.regex, r"\d+")
self.assertEqual(request.json_schema, '{"type": "object"}')
self.assertEqual(request.lora_path, "/path/to/lora")
def test_completion_request_validation_errors(self):
"""Test completion request validation errors"""
with self.assertRaises(ValidationError):
CompletionRequest() # missing required fields
with self.assertRaises(ValidationError):
CompletionRequest(model="test-model") # missing prompt
class TestChatCompletionRequest(unittest.TestCase):
"""Test ChatCompletionRequest protocol model"""
def test_json_schema_strict_requires_json_boolean(self):
base_request = {
"model": "test-model",
"messages": [{"role": "user", "content": "Hello"}],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "answer",
"schema": {"type": "object"},
},
},
}
for strict in (True, False, None):
with self.subTest(strict=strict):
response_format = dict(base_request["response_format"])
response_format["json_schema"] = {
**response_format["json_schema"],
"strict": strict,
}
request = ChatCompletionRequest.model_validate(
{**base_request, "response_format": response_format}
)
self.assertIs(request.response_format.json_schema.strict, strict)
for strict in ("yes", "false", 0, 1):
with self.subTest(strict=strict), self.assertRaises(ValidationError):
response_format = dict(base_request["response_format"])
response_format["json_schema"] = {
**response_format["json_schema"],
"strict": strict,
}
ChatCompletionRequest.model_validate(
{**base_request, "response_format": response_format}
)
def test_basic_chat_completion_request(self):
"""Test basic chat completion request"""
messages = [{"role": "user", "content": "Hello"}]
request = ChatCompletionRequest(model="test-model", messages=messages)
self.assertEqual(request.model, "test-model")
self.assertEqual(len(request.messages), 1)
self.assertEqual(request.messages[0].role, "user")
self.assertEqual(request.messages[0].content, "Hello")
self.assertEqual(request.temperature, None) # default
self.assertFalse(request.stream) # default
self.assertFalse(request.return_sampling_mask)
self.assertEqual(request.tool_choice, "none") # default when no tools
def test_image_content_hash_validation(self):
digest = "sha256:" + "AB" * 32
image = ChatCompletionMessageContentImageURL(
url="https://example.com/image.jpg", content_hash=digest
)
self.assertEqual(image.content_hash, digest.lower())
with self.assertRaises(ValidationError):
ChatCompletionMessageContentImageURL(
url="https://example.com/image.jpg", content_hash="not-a-hash"
)
def test_sampling_param_build(self):
req = ChatCompletionRequest(
model="x",
messages=[{"role": "user", "content": "Hi"}],
temperature=0.8,
max_tokens=150,
min_tokens=5,
top_p=0.9,
stop=["</s>"],
)
params = req.to_sampling_params(["</s>"], {}, None)
self.assertEqual(params["temperature"], 0.8)
self.assertEqual(params["max_new_tokens"], 150)
self.assertEqual(params["min_new_tokens"], 5)
self.assertEqual(params["stop"], ["</s>"])
def test_chat_completion_tool_choice_validation(self):
"""Test tool choice validation logic"""
messages = [{"role": "user", "content": "Hello"}]
# No tools, tool_choice should default to "none"
request1 = ChatCompletionRequest(model="test-model", messages=messages)
self.assertEqual(request1.tool_choice, "none")
# With tools, tool_choice should default to "auto"
tools = [
{
"type": "function",
"function": {"name": "test_func", "description": "Test function"},
}
]
request2 = ChatCompletionRequest(
model="test-model", messages=messages, tools=tools
)
self.assertEqual(request2.tool_choice, "auto")
def test_chat_completion_sglang_extensions(self):
"""Test chat completion with SGLang extensions"""
messages = [{"role": "user", "content": "Hello"}]
request = ChatCompletionRequest(
model="test-model",
messages=messages,
top_k=40,
min_p=0.05,
separate_reasoning=False,
stream_reasoning=False,
chat_template_kwargs={"custom_param": "value"},
)
self.assertEqual(request.top_k, 40)
self.assertEqual(request.min_p, 0.05)
self.assertFalse(request.separate_reasoning)
self.assertFalse(request.stream_reasoning)
self.assertEqual(request.chat_template_kwargs, {"custom_param": "value"})
def test_chat_completion_tito_extensions(self):
"""Test chat completion with pre-tokenized prompt extensions."""
messages = [{"role": "user", "content": "Hello"}]
request = ChatCompletionRequest(
model="test-model",
messages=messages,
input_ids=[101, 102, 103],
return_prompt_token_ids=True,
return_meta_info=True,
)
self.assertEqual(request.input_ids, [101, 102, 103])
self.assertTrue(request.return_prompt_token_ids)
self.assertTrue(request.return_meta_info)
def test_chat_completion_reasoning_effort(self):
"""Test chat completion with reasoning effort"""
messages = [{"role": "user", "content": "Hello"}]
request = ChatCompletionRequest(
model="test-model",
messages=messages,
reasoning={
"enabled": True,
"reasoning_effort": "high",
},
)
self.assertEqual(request.reasoning_effort, "high")
self.assertEqual(
request.chat_template_kwargs,
{"thinking": True, "enable_thinking": True},
)
def test_chat_completion_reasoning_effort_high_enables_thinking(self):
"""Top-level reasoning_effort='high' enables thinking."""
messages = [{"role": "user", "content": "Hello"}]
request = ChatCompletionRequest(
model="test-model",
messages=messages,
reasoning_effort="high",
)
self.assertEqual(request.reasoning_effort, "high")
self.assertEqual(
request.chat_template_kwargs,
{"thinking": True, "enable_thinking": True},
)
def test_chat_completion_reasoning_effort_none(self):
"""Test reasoning_effort='none' disables thinking"""
messages = [{"role": "user", "content": "Hello"}]
request = ChatCompletionRequest(
model="test-model",
messages=messages,
reasoning_effort="none",
)
self.assertEqual(request.reasoning_effort, "none")
self.assertFalse(request.chat_template_kwargs.get("thinking"))
self.assertFalse(request.chat_template_kwargs.get("enable_thinking"))
def test_chat_completion_reasoning_effort_none_from_reasoning_dict(self):
"""Test reasoning_effort='none' via nested reasoning dict"""
messages = [{"role": "user", "content": "Hello"}]
request = ChatCompletionRequest(
model="test-model",
messages=messages,
reasoning={"effort": "none"},
)
self.assertEqual(request.reasoning_effort, "none")
self.assertFalse(request.chat_template_kwargs.get("thinking"))
self.assertFalse(request.chat_template_kwargs.get("enable_thinking"))
def test_chat_completion_reasoning_effort_none_overrides_enabled(self):
messages = [{"role": "user", "content": "Hello"}]
request = ChatCompletionRequest(
model="test-model",
messages=messages,
reasoning={"enabled": True, "effort": "none"},
)
self.assertEqual(request.reasoning_effort, "none")
self.assertFalse(request.chat_template_kwargs.get("thinking"))
self.assertFalse(request.chat_template_kwargs.get("enable_thinking"))
def test_chat_completion_extended_reasoning_effort_levels(self):
"""Extended effort levels work in both supported request forms."""
from pydantic import ValidationError
messages = [{"role": "user", "content": "Hello"}]
for effort in ("xhigh", "max"):
with self.subTest(effort=effort, request_form="top-level"):
request = ChatCompletionRequest(
model="test-model",
messages=messages,
reasoning_effort=effort,
)
self.assertEqual(request.reasoning_effort, effort)
with self.subTest(effort=effort, request_form="nested"):
request = ChatCompletionRequest(
model="test-model",
messages=messages,
reasoning={"effort": effort},
)
self.assertEqual(request.reasoning_effort, effort)
# Unknown values still rejected.
with self.assertRaises(ValidationError):
ChatCompletionRequest(
model="test-model",
messages=messages,
reasoning_effort="ultra",
)
def test_chat_completion_reasoning_effort_is_strictly_validated(self):
from pydantic import ValidationError
messages = [{"role": "user", "content": "Hello"}]
for request_kwargs, expected in (
({"reasoning_effort": 0.99}, 0.99),
({"reasoning": {"effort": 0.0}}, 0.0),
# numeric strings coerce identically on BOTH request surfaces
# (the top-level field's lax union already coerced them).
({"reasoning": {"effort": "0.5"}}, 0.5),
({"reasoning": {"effort": None, "reasoning_effort": 0.4}}, 0.4),
):
request = ChatCompletionRequest(
model="test-model", messages=messages, **request_kwargs
)
self.assertEqual(request.reasoning_effort, expected)
for request_kwargs in (
{"reasoning_effort": -0.1},
# 0.99 is the maximum valid effort; 1.0 is out of range.
{"reasoning_effort": 1.0},
{"reasoning_effort": 1.1},
{"reasoning_effort": float("nan")},
{"reasoning_effort": True},
{"reasoning": {"effort": "invalid"}},
{"reasoning": {"effort": 1.0}},
{"reasoning": {"effort": 1.1}},
{"reasoning": {"effort": "1.5"}},
):
with self.subTest(request_kwargs=request_kwargs), self.assertRaises(
ValidationError
):
ChatCompletionRequest(
model="test-model", messages=messages, **request_kwargs
)
def test_chat_completion_accepts_ordered_thinking_parts(self):
request = ChatCompletionRequest(
model="test-model",
messages=[
{
"role": "assistant",
"content": [
{"type": "thinking", "thinking": "first"},
{"type": "text", "text": "visible"},
{"type": "reasoning", "text": "second"},
],
}
],
)
parts = request.messages[0].content
self.assertEqual(
[part.type for part in parts], ["thinking", "text", "reasoning"]
)
def test_chat_completion_rejects_thinking_parts_outside_assistant(self):
"""Bug regression: adding the thinking part to the SHARED content-part
union silently widened acceptance to every role (user/system/tool) and
every model family, where downstream templates cannot render it —
replacing the previous clean 422 with template-dependent behavior."""
from pydantic import ValidationError
for role in ("user", "system", "tool"):
with self.subTest(role=role), self.assertRaises(ValidationError):
ChatCompletionRequest(
model="test-model",
messages=[
{
"role": role,
"content": [{"type": "thinking", "thinking": "x"}],
}
],
)
def test_chat_completion_json_format(self):
"""Test chat completion json format"""
transcript = "Good morning! It's 7:00 AM, and I'm just waking up. Today is going to be a busy day, "
"so let's get started. First, I need to make a quick breakfast. I think I'll have some "
"scrambled eggs and toast with a cup of coffee. While I'm cooking, I'll also check my "
"emails to see if there's anything urgent."
messages = [
{
"role": "system",
"content": "The following is a voice message transcript. Only answer in JSON.",
},
{
"role": "user",
"content": transcript,
},
]
class VoiceNote(BaseModel):
title: str = Field(description="A title for the voice note")
summary: str = Field(
description="A short one sentence summary of the voice note."
)
strict: Optional[bool] = True
actionItems: List[str] = Field(
description="A list of action items from the voice note"
)
request = ChatCompletionRequest(
model="test-model",
messages=messages,
top_k=40,
min_p=0.05,
separate_reasoning=False,
stream_reasoning=False,
chat_template_kwargs={"custom_param": "value"},
response_format={
"type": "json_schema",
"schema": VoiceNote.model_json_schema(),
},
)
res_format = request.response_format
json_format = res_format.json_schema
name = json_format.name
schema = json_format.schema_
strict = json_format.strict
self.assertEqual(name, "VoiceNote")
self.assertEqual(strict, True)
self.assertNotIn("strict", schema["properties"])
request = ChatCompletionRequest(
model="test-model",
messages=messages,
top_k=40,
min_p=0.05,
separate_reasoning=False,
stream_reasoning=False,
chat_template_kwargs={"custom_param": "value"},
response_format={
"type": "json_schema",
"json_schema": {
"name": "VoiceNote",
"schema": VoiceNote.model_json_schema(),
"strict": True,
},
},
)
res_format = request.response_format
json_format = res_format.json_schema
name = json_format.name
schema = json_format.schema_
strict = json_format.strict
self.assertEqual(name, "VoiceNote")
self.assertEqual(strict, True)
def test_schema_derived_strict_false_constraint_gated_on_renderer(self):
"""A `strict` field on the user's model doubles as the protocol switch.
set_json_schema pops `strict` out of the schema's properties and feeds
its default into response_format. strict=False drops the sampling
constraint only when the renderer forwards response_format to the
model; otherwise the schema would be silently ignored, so the
constraint stays installed.
"""
class Note(BaseModel):
title: str
strict: bool = False
request = ChatCompletionRequest(
model="test-model",
messages=[{"role": "user", "content": "Return JSON"}],
response_format={
"type": "json_schema",
"schema": Note.model_json_schema(),
},
)
self.assertIs(request.response_format.json_schema.strict, False)
self.assertNotIn(
"strict", request.response_format.json_schema.schema_["properties"]
)
sampling_params = request.to_sampling_params(
stop=[], model_generation_config={}
)
self.assertIn("json_schema", sampling_params)
sampling_params = request.to_sampling_params(
stop=[],
model_generation_config={},
renderer_handles_response_format=True,
)
self.assertNotIn("json_schema", sampling_params)
def test_non_strict_response_format_constraint_gated_on_renderer(self):
request = ChatCompletionRequest(
model="test-model",
messages=[{"role": "user", "content": "Return JSON"}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "answer",
"schema": {"type": "object"},
"strict": False,
},
},
)
sampling_params = request.to_sampling_params(
stop=[], model_generation_config={}
)
self.assertIn("json_schema", sampling_params)
sampling_params = request.to_sampling_params(
stop=[],
model_generation_config={},
renderer_handles_response_format=True,
)
self.assertNotIn("json_schema", sampling_params)
class TestModelSerialization(unittest.TestCase):
"""Test model serialization with hidden states"""
def test_hidden_states_excluded_when_none(self):
"""Test that None hidden_states are excluded with exclude_none=True"""
choice = ChatCompletionResponseChoice(
index=0,
message=ChatMessage(role="assistant", content="Hello"),
finish_reason="stop",
hidden_states=None,
)
response = ChatCompletionResponse(
id="test-id",
model="test-model",
choices=[choice],
usage=UsageInfo(prompt_tokens=5, completion_tokens=1, total_tokens=6),
)
# Test exclude_none serialization (should exclude None hidden_states)
data = response.model_dump(exclude_none=True)
self.assertNotIn("hidden_states", data["choices"][0])
def test_hidden_states_included_when_not_none(self):
"""Test that non-None hidden_states are included"""
choice = ChatCompletionResponseChoice(
index=0,
message=ChatMessage(role="assistant", content="Hello"),
finish_reason="stop",
hidden_states=[0.1, 0.2, 0.3],
)
response = ChatCompletionResponse(
id="test-id",
model="test-model",
choices=[choice],
usage=UsageInfo(prompt_tokens=5, completion_tokens=1, total_tokens=6),
)
# Test exclude_none serialization (should include non-None hidden_states)
data = response.model_dump(exclude_none=True)
self.assertIn("hidden_states", data["choices"][0])
self.assertEqual(data["choices"][0]["hidden_states"], [0.1, 0.2, 0.3])
def test_prompt_token_ids_and_meta_info_serialization(self):
"""Test that prompt_token_ids and meta_info serialize only when set."""
default_choice = ChatCompletionResponseChoice(
index=0,
message=ChatMessage(role="assistant", content="Hello"),
finish_reason="stop",
)
default_data = default_choice.model_dump()
self.assertNotIn("prompt_token_ids", default_data)
self.assertNotIn("response_token_ids", default_data)
self.assertNotIn("meta_info", default_data)
choice = ChatCompletionResponseChoice(
index=0,
message=ChatMessage(role="assistant", content="Hello"),
finish_reason="stop",
prompt_token_ids=[1, 2, 3],
response_token_ids=[4, 5],
meta_info={"prompt_tokens": 3},
)
data = choice.model_dump()
self.assertEqual(data["prompt_token_ids"], [1, 2, 3])
self.assertNotIn("token_ids", data)
self.assertEqual(data["response_token_ids"], [4, 5])
self.assertEqual(data["meta_info"], {"prompt_tokens": 3})
class TestFunctionDeferLoading(unittest.TestCase):
"""Test defer_loading field behavior on Function/Tool."""
def test_function_defaults_preserve_strict(self):
"""strict must default to False and be present in dumps so downstream
code (function_call_parser, chat templates) sees the expected shape."""
f = Function(name="foo")
data = f.model_dump()
self.assertEqual(data["name"], "foo")
self.assertEqual(data["strict"], False)
self.assertNotIn("defer_loading", data)
def test_function_defer_loading_true_serialized(self):
f = Function(name="foo", defer_loading=True)
data = f.model_dump()
self.assertTrue(data["defer_loading"])
self.assertEqual(data["strict"], False)
def test_function_defer_loading_false_serialized(self):
"""defer_loading=False is an explicit value and must be preserved."""
f = Function(name="foo", defer_loading=False)
data = f.model_dump()
self.assertIn("defer_loading", data)
self.assertFalse(data["defer_loading"])
def test_tool_level_defer_loading_propagates_to_function(self):
"""defer_loading at the Tool level should propagate to Function."""
tool = Tool(
type="function",
defer_loading=True,
function={"name": "search_db"},
)
self.assertTrue(tool.function.defer_loading)
data = tool.model_dump()
self.assertTrue(data["function"]["defer_loading"])
def test_function_level_defer_loading_wins_over_tool_level(self):
"""Explicit function-level value is preserved when both set."""
tool = Tool(
type="function",
defer_loading=True,
function={"name": "search_db", "defer_loading": False},
)
self.assertFalse(tool.function.defer_loading)
def test_tool_reference_content_part_accepted(self):
"""Chat completion should accept tool_reference content on tool-role
messages (GLM-specific extension consumed by the chat template)."""
messages = [
{
"role": "tool",
"tool_call_id": "call_1",
"content": [
{"type": "tool_reference", "name": "search_db"},
{"type": "text", "text": "ok"},
],
},
]
request = ChatCompletionRequest(model="test-model", messages=messages)
parts = request.messages[0].content
self.assertEqual(len(parts), 2)
self.assertEqual(parts[0].type, "tool_reference")
self.assertEqual(parts[0].name, "search_db")
self.assertEqual(parts[1].type, "text")
class TestValidationEdgeCases(unittest.TestCase):
"""Test edge cases and validation scenarios"""
def test_invalid_tool_choice_type(self):
"""Test invalid tool choice type"""
messages = [{"role": "user", "content": "Hello"}]
with self.assertRaises(ValidationError):
ChatCompletionRequest(
model="test-model", messages=messages, tool_choice=123
)
def test_negative_token_limits(self):
"""Test negative token limits"""
with self.assertRaises(ValidationError):
CompletionRequest(model="test-model", prompt="Hello", max_tokens=-1)
class TestParsedResponseFieldsProtocol(unittest.TestCase):
"""Test ParsedResponseFields protocol."""
if __name__ == "__main__":
unittest.main(verbosity=2)