test_protocol.py 27.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 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 json
import time
18
import unittest
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from typing import Dict, List, Optional

from pydantic import ValidationError

from sglang.srt.entrypoints.openai.protocol import (
    BatchRequest,
    BatchResponse,
    ChatCompletionMessageContentImagePart,
    ChatCompletionMessageContentTextPart,
    ChatCompletionRequest,
    ChatCompletionResponse,
    ChatCompletionResponseChoice,
    ChatCompletionResponseStreamChoice,
    ChatCompletionStreamResponse,
    ChatCompletionTokenLogprob,
    ChatMessage,
    ChoiceLogprobs,
    CompletionRequest,
    CompletionResponse,
    CompletionResponseChoice,
    DeltaMessage,
    EmbeddingObject,
    EmbeddingRequest,
    EmbeddingResponse,
    ErrorResponse,
    FileDeleteResponse,
    FileRequest,
    FileResponse,
    Function,
    FunctionResponse,
    JsonSchemaResponseFormat,
    LogProbs,
    ModelCard,
    ModelList,
    MultimodalEmbeddingInput,
    ResponseFormat,
    ScoringRequest,
    ScoringResponse,
    StreamOptions,
    StructuralTagResponseFormat,
    Tool,
    ToolCall,
    ToolChoice,
    TopLogprob,
    UsageInfo,
)


67
class TestModelCard(unittest.TestCase):
68
69
70
71
72
    """Test ModelCard protocol model"""

    def test_basic_model_card_creation(self):
        """Test basic model card creation with required fields"""
        card = ModelCard(id="test-model")
73
74
75
76
77
78
        self.assertEqual(card.id, "test-model")
        self.assertEqual(card.object, "model")
        self.assertEqual(card.owned_by, "sglang")
        self.assertIsInstance(card.created, int)
        self.assertIsNone(card.root)
        self.assertIsNone(card.max_model_len)
79
80
81
82
83
84
85
86
87

    def test_model_card_with_optional_fields(self):
        """Test model card with optional fields"""
        card = ModelCard(
            id="test-model",
            root="/path/to/model",
            max_model_len=2048,
            created=1234567890,
        )
88
89
90
91
        self.assertEqual(card.id, "test-model")
        self.assertEqual(card.root, "/path/to/model")
        self.assertEqual(card.max_model_len, 2048)
        self.assertEqual(card.created, 1234567890)
92
93
94
95
96

    def test_model_card_serialization(self):
        """Test model card JSON serialization"""
        card = ModelCard(id="test-model", max_model_len=4096)
        data = card.model_dump()
97
98
99
        self.assertEqual(data["id"], "test-model")
        self.assertEqual(data["object"], "model")
        self.assertEqual(data["max_model_len"], 4096)
100
101


102
class TestModelList(unittest.TestCase):
103
104
105
106
107
    """Test ModelList protocol model"""

    def test_empty_model_list(self):
        """Test empty model list creation"""
        model_list = ModelList()
108
109
        self.assertEqual(model_list.object, "list")
        self.assertEqual(len(model_list.data), 0)
110
111
112
113
114
115
116
117

    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)
118
119
120
        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")
121
122


123
class TestErrorResponse(unittest.TestCase):
124
125
126
127
128
129
130
    """Test ErrorResponse protocol model"""

    def test_basic_error_response(self):
        """Test basic error response creation"""
        error = ErrorResponse(
            message="Invalid request", type="BadRequestError", code=400
        )
131
132
133
134
135
        self.assertEqual(error.object, "error")
        self.assertEqual(error.message, "Invalid request")
        self.assertEqual(error.type, "BadRequestError")
        self.assertEqual(error.code, 400)
        self.assertIsNone(error.param)
136
137
138
139
140
141
142
143
144

    def test_error_response_with_param(self):
        """Test error response with parameter"""
        error = ErrorResponse(
            message="Invalid temperature",
            type="ValidationError",
            code=422,
            param="temperature",
        )
145
        self.assertEqual(error.param, "temperature")
146
147


148
class TestUsageInfo(unittest.TestCase):
149
150
151
152
153
    """Test UsageInfo protocol model"""

    def test_basic_usage_info(self):
        """Test basic usage info creation"""
        usage = UsageInfo(prompt_tokens=10, completion_tokens=20, total_tokens=30)
154
155
156
157
        self.assertEqual(usage.prompt_tokens, 10)
        self.assertEqual(usage.completion_tokens, 20)
        self.assertEqual(usage.total_tokens, 30)
        self.assertIsNone(usage.prompt_tokens_details)
158
159
160
161
162
163
164
165
166

    def test_usage_info_with_cache_details(self):
        """Test usage info with cache details"""
        usage = UsageInfo(
            prompt_tokens=10,
            completion_tokens=20,
            total_tokens=30,
            prompt_tokens_details={"cached_tokens": 5},
        )
167
        self.assertEqual(usage.prompt_tokens_details, {"cached_tokens": 5})
168
169


170
class TestCompletionRequest(unittest.TestCase):
171
172
173
174
175
    """Test CompletionRequest protocol model"""

    def test_basic_completion_request(self):
        """Test basic completion request"""
        request = CompletionRequest(model="test-model", prompt="Hello world")
176
177
178
179
180
181
182
        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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197

    def test_completion_request_with_options(self):
        """Test completion request with various options"""
        request = CompletionRequest(
            model="test-model",
            prompt=["Hello", "world"],
            max_tokens=100,
            temperature=0.7,
            top_p=0.9,
            n=2,
            stream=True,
            echo=True,
            stop=[".", "!"],
            logprobs=5,
        )
198
199
200
201
202
203
204
205
206
        self.assertEqual(request.prompt, ["Hello", "world"])
        self.assertEqual(request.max_tokens, 100)
        self.assertEqual(request.temperature, 0.7)
        self.assertEqual(request.top_p, 0.9)
        self.assertEqual(request.n, 2)
        self.assertTrue(request.stream)
        self.assertTrue(request.echo)
        self.assertEqual(request.stop, [".", "!"])
        self.assertEqual(request.logprobs, 5)
207
208
209
210
211
212
213
214
215
216
217
218
219

    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",
        )
220
221
222
223
224
225
        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")
226
227
228

    def test_completion_request_validation_errors(self):
        """Test completion request validation errors"""
229
        with self.assertRaises(ValidationError):
230
231
            CompletionRequest()  # missing required fields

232
        with self.assertRaises(ValidationError):
233
234
235
            CompletionRequest(model="test-model")  # missing prompt


236
class TestCompletionResponse(unittest.TestCase):
237
238
239
240
241
242
243
244
245
246
247
    """Test CompletionResponse protocol model"""

    def test_basic_completion_response(self):
        """Test basic completion response"""
        choice = CompletionResponseChoice(
            index=0, text="Hello world!", finish_reason="stop"
        )
        usage = UsageInfo(prompt_tokens=2, completion_tokens=3, total_tokens=5)
        response = CompletionResponse(
            id="test-id", model="test-model", choices=[choice], usage=usage
        )
248
249
250
251
252
253
        self.assertEqual(response.id, "test-id")
        self.assertEqual(response.object, "text_completion")
        self.assertEqual(response.model, "test-model")
        self.assertEqual(len(response.choices), 1)
        self.assertEqual(response.choices[0].text, "Hello world!")
        self.assertEqual(response.usage.total_tokens, 5)
254
255


256
class TestChatCompletionRequest(unittest.TestCase):
257
258
259
260
261
262
    """Test ChatCompletionRequest protocol model"""

    def test_basic_chat_completion_request(self):
        """Test basic chat completion request"""
        messages = [{"role": "user", "content": "Hello"}]
        request = ChatCompletionRequest(model="test-model", messages=messages)
263
264
265
266
267
268
269
        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, 0.7)  # default
        self.assertFalse(request.stream)  # default
        self.assertEqual(request.tool_choice, "none")  # default when no tools
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285

    def test_chat_completion_with_multimodal_content(self):
        """Test chat completion with multimodal content"""
        messages = [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "What's in this image?"},
                    {
                        "type": "image_url",
                        "image_url": {"url": "data:image/jpeg;base64,/9j/4AAQ..."},
                    },
                ],
            }
        ]
        request = ChatCompletionRequest(model="test-model", messages=messages)
286
287
288
        self.assertEqual(len(request.messages[0].content), 2)
        self.assertEqual(request.messages[0].content[0].type, "text")
        self.assertEqual(request.messages[0].content[1].type, "image_url")
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308

    def test_chat_completion_with_tools(self):
        """Test chat completion with tools"""
        messages = [{"role": "user", "content": "What's the weather?"}]
        tools = [
            {
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "description": "Get weather information",
                    "parameters": {
                        "type": "object",
                        "properties": {"location": {"type": "string"}},
                    },
                },
            }
        ]
        request = ChatCompletionRequest(
            model="test-model", messages=messages, tools=tools
        )
309
310
311
        self.assertEqual(len(request.tools), 1)
        self.assertEqual(request.tools[0].function.name, "get_weather")
        self.assertEqual(request.tool_choice, "auto")  # default when tools present
312
313
314
315
316
317
318

    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)
319
        self.assertEqual(request1.tool_choice, "none")
320
321
322
323
324
325
326
327
328
329
330

        # 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
        )
331
        self.assertEqual(request2.tool_choice, "auto")
332
333
334
335
336
337
338
339
340
341
342
343
344

    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"},
        )
345
346
347
348
349
        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"})
350
351


352
class TestChatCompletionResponse(unittest.TestCase):
353
354
355
356
357
358
359
360
361
362
363
364
    """Test ChatCompletionResponse protocol model"""

    def test_basic_chat_completion_response(self):
        """Test basic chat completion response"""
        message = ChatMessage(role="assistant", content="Hello there!")
        choice = ChatCompletionResponseChoice(
            index=0, message=message, finish_reason="stop"
        )
        usage = UsageInfo(prompt_tokens=2, completion_tokens=3, total_tokens=5)
        response = ChatCompletionResponse(
            id="test-id", model="test-model", choices=[choice], usage=usage
        )
365
366
367
368
369
        self.assertEqual(response.id, "test-id")
        self.assertEqual(response.object, "chat.completion")
        self.assertEqual(response.model, "test-model")
        self.assertEqual(len(response.choices), 1)
        self.assertEqual(response.choices[0].message.content, "Hello there!")
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386

    def test_chat_completion_response_with_tool_calls(self):
        """Test chat completion response with tool calls"""
        tool_call = ToolCall(
            id="call_123",
            function=FunctionResponse(
                name="get_weather", arguments='{"location": "San Francisco"}'
            ),
        )
        message = ChatMessage(role="assistant", content=None, tool_calls=[tool_call])
        choice = ChatCompletionResponseChoice(
            index=0, message=message, finish_reason="tool_calls"
        )
        usage = UsageInfo(prompt_tokens=10, completion_tokens=5, total_tokens=15)
        response = ChatCompletionResponse(
            id="test-id", model="test-model", choices=[choice], usage=usage
        )
387
388
389
390
        self.assertEqual(
            response.choices[0].message.tool_calls[0].function.name, "get_weather"
        )
        self.assertEqual(response.choices[0].finish_reason, "tool_calls")
391
392


393
class TestEmbeddingRequest(unittest.TestCase):
394
395
396
397
398
    """Test EmbeddingRequest protocol model"""

    def test_basic_embedding_request(self):
        """Test basic embedding request"""
        request = EmbeddingRequest(model="test-model", input="Hello world")
399
400
401
402
        self.assertEqual(request.model, "test-model")
        self.assertEqual(request.input, "Hello world")
        self.assertEqual(request.encoding_format, "float")  # default
        self.assertIsNone(request.dimensions)  # default
403
404
405
406
407
408

    def test_embedding_request_with_list_input(self):
        """Test embedding request with list input"""
        request = EmbeddingRequest(
            model="test-model", input=["Hello", "world"], dimensions=512
        )
409
410
        self.assertEqual(request.input, ["Hello", "world"])
        self.assertEqual(request.dimensions, 512)
411
412
413
414
415
416
417
418

    def test_multimodal_embedding_request(self):
        """Test multimodal embedding request"""
        multimodal_input = [
            MultimodalEmbeddingInput(text="Hello", image="base64_image_data"),
            MultimodalEmbeddingInput(text="World", image=None),
        ]
        request = EmbeddingRequest(model="test-model", input=multimodal_input)
419
420
421
422
423
        self.assertEqual(len(request.input), 2)
        self.assertEqual(request.input[0].text, "Hello")
        self.assertEqual(request.input[0].image, "base64_image_data")
        self.assertEqual(request.input[1].text, "World")
        self.assertIsNone(request.input[1].image)
424
425


426
class TestEmbeddingResponse(unittest.TestCase):
427
428
429
430
431
432
433
434
435
    """Test EmbeddingResponse protocol model"""

    def test_basic_embedding_response(self):
        """Test basic embedding response"""
        embedding_obj = EmbeddingObject(embedding=[0.1, 0.2, 0.3], index=0)
        usage = UsageInfo(prompt_tokens=3, total_tokens=3)
        response = EmbeddingResponse(
            data=[embedding_obj], model="test-model", usage=usage
        )
436
437
438
439
440
        self.assertEqual(response.object, "list")
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0].embedding, [0.1, 0.2, 0.3])
        self.assertEqual(response.data[0].index, 0)
        self.assertEqual(response.usage.prompt_tokens, 3)
441
442


443
class TestScoringRequest(unittest.TestCase):
444
445
446
447
448
449
450
    """Test ScoringRequest protocol model"""

    def test_basic_scoring_request(self):
        """Test basic scoring request"""
        request = ScoringRequest(
            model="test-model", query="Hello", items=["World", "Earth"]
        )
451
452
453
454
455
        self.assertEqual(request.model, "test-model")
        self.assertEqual(request.query, "Hello")
        self.assertEqual(request.items, ["World", "Earth"])
        self.assertFalse(request.apply_softmax)  # default
        self.assertFalse(request.item_first)  # default
456
457
458
459
460
461
462
463
464
465
466

    def test_scoring_request_with_token_ids(self):
        """Test scoring request with token IDs"""
        request = ScoringRequest(
            model="test-model",
            query=[1, 2, 3],
            items=[[4, 5], [6, 7]],
            label_token_ids=[8, 9],
            apply_softmax=True,
            item_first=True,
        )
467
468
469
470
471
        self.assertEqual(request.query, [1, 2, 3])
        self.assertEqual(request.items, [[4, 5], [6, 7]])
        self.assertEqual(request.label_token_ids, [8, 9])
        self.assertTrue(request.apply_softmax)
        self.assertTrue(request.item_first)
472
473


474
class TestScoringResponse(unittest.TestCase):
475
476
477
478
479
    """Test ScoringResponse protocol model"""

    def test_basic_scoring_response(self):
        """Test basic scoring response"""
        response = ScoringResponse(scores=[[0.1, 0.9], [0.3, 0.7]], model="test-model")
480
481
482
483
        self.assertEqual(response.object, "scoring")
        self.assertEqual(response.scores, [[0.1, 0.9], [0.3, 0.7]])
        self.assertEqual(response.model, "test-model")
        self.assertIsNone(response.usage)  # default
484
485


486
class TestFileOperations(unittest.TestCase):
487
488
489
490
491
492
    """Test file operation protocol models"""

    def test_file_request(self):
        """Test file request model"""
        file_data = b"test file content"
        request = FileRequest(file=file_data, purpose="batch")
493
494
        self.assertEqual(request.file, file_data)
        self.assertEqual(request.purpose, "batch")
495
496
497
498
499
500
501
502
503
504

    def test_file_response(self):
        """Test file response model"""
        response = FileResponse(
            id="file-123",
            bytes=1024,
            created_at=1234567890,
            filename="test.jsonl",
            purpose="batch",
        )
505
506
507
508
        self.assertEqual(response.id, "file-123")
        self.assertEqual(response.object, "file")
        self.assertEqual(response.bytes, 1024)
        self.assertEqual(response.filename, "test.jsonl")
509
510
511
512

    def test_file_delete_response(self):
        """Test file delete response model"""
        response = FileDeleteResponse(id="file-123", deleted=True)
513
514
515
        self.assertEqual(response.id, "file-123")
        self.assertEqual(response.object, "file")
        self.assertTrue(response.deleted)
516
517


518
class TestBatchOperations(unittest.TestCase):
519
520
521
522
523
524
525
526
527
528
    """Test batch operation protocol models"""

    def test_batch_request(self):
        """Test batch request model"""
        request = BatchRequest(
            input_file_id="file-123",
            endpoint="/v1/chat/completions",
            completion_window="24h",
            metadata={"custom": "value"},
        )
529
530
531
532
        self.assertEqual(request.input_file_id, "file-123")
        self.assertEqual(request.endpoint, "/v1/chat/completions")
        self.assertEqual(request.completion_window, "24h")
        self.assertEqual(request.metadata, {"custom": "value"})
533
534
535
536
537
538
539
540
541
542

    def test_batch_response(self):
        """Test batch response model"""
        response = BatchResponse(
            id="batch-123",
            endpoint="/v1/chat/completions",
            input_file_id="file-123",
            completion_window="24h",
            created_at=1234567890,
        )
543
544
545
546
        self.assertEqual(response.id, "batch-123")
        self.assertEqual(response.object, "batch")
        self.assertEqual(response.status, "validating")  # default
        self.assertEqual(response.endpoint, "/v1/chat/completions")
547
548


549
class TestResponseFormats(unittest.TestCase):
550
551
552
553
554
    """Test response format protocol models"""

    def test_basic_response_format(self):
        """Test basic response format"""
        format_obj = ResponseFormat(type="json_object")
555
556
        self.assertEqual(format_obj.type, "json_object")
        self.assertIsNone(format_obj.json_schema)
557
558
559
560
561
562
563
564

    def test_json_schema_response_format(self):
        """Test JSON schema response format"""
        schema = {"type": "object", "properties": {"name": {"type": "string"}}}
        json_schema = JsonSchemaResponseFormat(
            name="person_schema", description="Person schema", schema=schema
        )
        format_obj = ResponseFormat(type="json_schema", json_schema=json_schema)
565
566
567
        self.assertEqual(format_obj.type, "json_schema")
        self.assertEqual(format_obj.json_schema.name, "person_schema")
        self.assertEqual(format_obj.json_schema.schema_, schema)
568
569
570
571
572
573
574
575
576
577
578
579
580

    def test_structural_tag_response_format(self):
        """Test structural tag response format"""
        structures = [
            {
                "begin": "<thinking>",
                "schema_": {"type": "string"},
                "end": "</thinking>",
            }
        ]
        format_obj = StructuralTagResponseFormat(
            type="structural_tag", structures=structures, triggers=["think"]
        )
581
582
583
        self.assertEqual(format_obj.type, "structural_tag")
        self.assertEqual(len(format_obj.structures), 1)
        self.assertEqual(format_obj.triggers, ["think"])
584
585


586
class TestLogProbs(unittest.TestCase):
587
588
589
590
591
592
593
594
595
596
    """Test LogProbs protocol models"""

    def test_basic_logprobs(self):
        """Test basic LogProbs model"""
        logprobs = LogProbs(
            text_offset=[0, 5, 11],
            token_logprobs=[-0.1, -0.2, -0.3],
            tokens=["Hello", " ", "world"],
            top_logprobs=[{"Hello": -0.1}, {" ": -0.2}, {"world": -0.3}],
        )
597
598
599
        self.assertEqual(len(logprobs.tokens), 3)
        self.assertEqual(logprobs.tokens, ["Hello", " ", "world"])
        self.assertEqual(logprobs.token_logprobs, [-0.1, -0.2, -0.3])
600
601
602
603
604
605
606
607
608
609
610
611

    def test_choice_logprobs(self):
        """Test ChoiceLogprobs model"""
        token_logprob = ChatCompletionTokenLogprob(
            token="Hello",
            bytes=[72, 101, 108, 108, 111],
            logprob=-0.1,
            top_logprobs=[
                TopLogprob(token="Hello", bytes=[72, 101, 108, 108, 111], logprob=-0.1)
            ],
        )
        choice_logprobs = ChoiceLogprobs(content=[token_logprob])
612
613
        self.assertEqual(len(choice_logprobs.content), 1)
        self.assertEqual(choice_logprobs.content[0].token, "Hello")
614
615


616
class TestStreamingModels(unittest.TestCase):
617
618
619
620
621
    """Test streaming response models"""

    def test_stream_options(self):
        """Test StreamOptions model"""
        options = StreamOptions(include_usage=True)
622
        self.assertTrue(options.include_usage)
623
624
625
626
627
628
629
630

    def test_chat_completion_stream_response(self):
        """Test ChatCompletionStreamResponse model"""
        delta = DeltaMessage(role="assistant", content="Hello")
        choice = ChatCompletionResponseStreamChoice(index=0, delta=delta)
        response = ChatCompletionStreamResponse(
            id="test-id", model="test-model", choices=[choice]
        )
631
632
        self.assertEqual(response.object, "chat.completion.chunk")
        self.assertEqual(response.choices[0].delta.content, "Hello")
633
634


635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
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])


680
class TestValidationEdgeCases(unittest.TestCase):
681
682
683
684
    """Test edge cases and validation scenarios"""

    def test_empty_messages_validation(self):
        """Test validation with empty messages"""
685
        with self.assertRaises(ValidationError):
686
687
688
689
690
            ChatCompletionRequest(model="test-model", messages=[])

    def test_invalid_tool_choice_type(self):
        """Test invalid tool choice type"""
        messages = [{"role": "user", "content": "Hello"}]
691
        with self.assertRaises(ValidationError):
692
693
694
695
696
697
            ChatCompletionRequest(
                model="test-model", messages=messages, tool_choice=123
            )

    def test_negative_token_limits(self):
        """Test negative token limits"""
698
        with self.assertRaises(ValidationError):
699
700
701
702
703
704
705
            CompletionRequest(model="test-model", prompt="Hello", max_tokens=-1)

    def test_invalid_temperature_range(self):
        """Test invalid temperature values"""
        # Note: The current protocol doesn't enforce temperature range,
        # but this test documents expected behavior
        request = CompletionRequest(model="test-model", prompt="Hello", temperature=5.0)
706
        self.assertEqual(request.temperature, 5.0)  # Currently allowed
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722

    def test_model_serialization_roundtrip(self):
        """Test that models can be serialized and deserialized"""
        original_request = ChatCompletionRequest(
            model="test-model",
            messages=[{"role": "user", "content": "Hello"}],
            temperature=0.7,
            max_tokens=100,
        )

        # Serialize to dict
        data = original_request.model_dump()

        # Deserialize back
        restored_request = ChatCompletionRequest(**data)

723
724
725
726
        self.assertEqual(restored_request.model, original_request.model)
        self.assertEqual(restored_request.temperature, original_request.temperature)
        self.assertEqual(restored_request.max_tokens, original_request.max_tokens)
        self.assertEqual(len(restored_request.messages), len(original_request.messages))
727
728
729


if __name__ == "__main__":
730
    unittest.main(verbosity=2)