test_serving_chat.py 21.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
"""
Unit tests for the OpenAIServingChat class from serving_chat.py.

These tests ensure that the refactored implementation maintains compatibility
with the original adapter.py functionality.
"""

import uuid
from unittest.mock import Mock, patch

import pytest
from fastapi import Request

from sglang.srt.entrypoints.openai.protocol import ChatCompletionRequest, ErrorResponse
from sglang.srt.entrypoints.openai.serving_chat import OpenAIServingChat
from sglang.srt.managers.io_struct import GenerateReqInput


# Mock TokenizerManager since it may not be directly importable in tests
class MockTokenizerManager:
    def __init__(self):
        self.model_config = Mock()
        self.model_config.is_multimodal = False
        self.server_args = Mock()
        self.server_args.enable_cache_report = False
        self.server_args.tool_call_parser = "hermes"
        self.server_args.reasoning_parser = None
        self.chat_template_name = "llama-3"

        # Mock tokenizer
        self.tokenizer = Mock()
        self.tokenizer.encode = Mock(return_value=[1, 2, 3, 4, 5])
        self.tokenizer.decode = Mock(return_value="Test response")
        self.tokenizer.chat_template = None
        self.tokenizer.bos_token_id = 1

        # Mock generate_request method
        async def mock_generate():
            yield {
                "text": "Test response",
                "meta_info": {
                    "id": f"chatcmpl-{uuid.uuid4()}",
                    "prompt_tokens": 10,
                    "completion_tokens": 5,
                    "cached_tokens": 0,
                    "finish_reason": {"type": "stop", "matched": None},
                    "output_token_logprobs": [(0.1, 1, "Test"), (0.2, 2, "response")],
                    "output_top_logprobs": None,
                },
                "index": 0,
            }

        self.generate_request = Mock(return_value=mock_generate())
        self.create_abort_task = Mock(return_value=None)


@pytest.fixture
def mock_tokenizer_manager():
    """Create a mock tokenizer manager for testing."""
    return MockTokenizerManager()


@pytest.fixture
def serving_chat(mock_tokenizer_manager):
    """Create a OpenAIServingChat instance for testing."""
    return OpenAIServingChat(mock_tokenizer_manager)


@pytest.fixture
def mock_request():
    """Create a mock FastAPI request."""
    request = Mock(spec=Request)
    request.headers = {}
    return request


@pytest.fixture
def basic_chat_request():
    """Create a basic chat completion request."""
    return ChatCompletionRequest(
        model="test-model",
        messages=[{"role": "user", "content": "Hello, how are you?"}],
        temperature=0.7,
        max_tokens=100,
        stream=False,
    )


@pytest.fixture
def streaming_chat_request():
    """Create a streaming chat completion request."""
    return ChatCompletionRequest(
        model="test-model",
        messages=[{"role": "user", "content": "Hello, how are you?"}],
        temperature=0.7,
        max_tokens=100,
        stream=True,
    )


class TestOpenAIServingChatConversion:
    """Test request conversion methods."""

    def test_convert_to_internal_request_single(
        self, serving_chat, basic_chat_request, mock_tokenizer_manager
    ):
        """Test converting single request to internal format."""
        with patch(
            "sglang.srt.entrypoints.openai.serving_chat.generate_chat_conv"
        ) as mock_conv:
            mock_conv_instance = Mock()
            mock_conv_instance.get_prompt.return_value = "Test prompt"
            mock_conv_instance.image_data = None
            mock_conv_instance.audio_data = None
            mock_conv_instance.modalities = []
            mock_conv_instance.stop_str = ["</s>"]
            mock_conv.return_value = mock_conv_instance

            # Mock the _process_messages method to return expected values
            with patch.object(serving_chat, "_process_messages") as mock_process:
                mock_process.return_value = (
                    "Test prompt",
                    [1, 2, 3],
                    None,
                    None,
                    [],
                    ["</s>"],
                    None,  # tool_call_constraint
                )

                adapted_request, processed_request = (
                    serving_chat._convert_to_internal_request(
                        [basic_chat_request], ["test-id"]
                    )
                )

                assert isinstance(adapted_request, GenerateReqInput)
                assert adapted_request.stream == basic_chat_request.stream
                assert processed_request == basic_chat_request


class TestToolCalls:
    """Test tool call functionality from adapter.py"""

    def test_tool_call_request_conversion(self, serving_chat):
        """Test request with tool calls"""
        request = ChatCompletionRequest(
            model="test-model",
            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"}},
                        },
                    },
                }
            ],
            tool_choice="auto",
        )

        with patch.object(serving_chat, "_process_messages") as mock_process:
            mock_process.return_value = (
                "Test prompt",
                [1, 2, 3],
                None,
                None,
                [],
                ["</s>"],
                None,  # tool_call_constraint
            )

            adapted_request, _ = serving_chat._convert_to_internal_request(
                [request], ["test-id"]
            )

            assert adapted_request.rid == "test-id"
            # Tool call constraint should be processed
            assert request.tools is not None

    def test_tool_choice_none(self, serving_chat):
        """Test tool_choice=none disables tool calls"""
        request = ChatCompletionRequest(
            model="test-model",
            messages=[{"role": "user", "content": "Hello"}],
            tools=[{"type": "function", "function": {"name": "test_func"}}],
            tool_choice="none",
        )

        with patch.object(serving_chat, "_process_messages") as mock_process:
            mock_process.return_value = (
                "Test prompt",
                [1, 2, 3],
                None,
                None,
                [],
                ["</s>"],
                None,  # tool_call_constraint
            )

            adapted_request, _ = serving_chat._convert_to_internal_request(
                [request], ["test-id"]
            )

            # Tools should not be processed when tool_choice is "none"
            assert adapted_request.rid == "test-id"

    def test_tool_call_response_processing(self, serving_chat):
        """Test processing tool calls in response"""
        mock_ret_item = {
            "text": '{"name": "get_weather", "parameters": {"location": "Paris"}}',
            "meta_info": {
                "output_token_logprobs": [],
                "output_top_logprobs": None,
            },
        }

        tools = [
            {
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "parameters": {
                        "type": "object",
                        "properties": {"location": {"type": "string"}},
                    },
                },
            }
        ]

        finish_reason = {"type": "stop", "matched": None}

        # Mock FunctionCallParser
        with patch(
            "sglang.srt.entrypoints.openai.serving_chat.FunctionCallParser"
        ) as mock_parser_class:
            mock_parser = Mock()
            mock_parser.has_tool_call.return_value = True

            # Create proper mock tool call object
            mock_tool_call = Mock()
            mock_tool_call.name = "get_weather"
            mock_tool_call.parameters = '{"location": "Paris"}'

            mock_parser.parse_non_stream.return_value = ("", [mock_tool_call])
            mock_parser_class.return_value = mock_parser

            tool_calls, text, updated_finish_reason = serving_chat._process_tool_calls(
                mock_ret_item["text"], tools, "hermes", finish_reason
            )

            assert tool_calls is not None
            assert len(tool_calls) == 1
            assert updated_finish_reason["type"] == "tool_calls"


class TestMultimodalContent:
    """Test multimodal content handling from adapter.py"""

    def test_multimodal_request_with_images(self, serving_chat):
        """Test request with image content"""
        request = ChatCompletionRequest(
            model="test-model",
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "What's in this image?"},
                        {
                            "type": "image_url",
                            "image_url": {"url": "data:image/jpeg;base64,..."},
                        },
                    ],
                }
            ],
        )

        # Set multimodal mode
        serving_chat.tokenizer_manager.model_config.is_multimodal = True

        with patch.object(serving_chat, "_apply_jinja_template") as mock_apply:
            mock_apply.return_value = (
                "prompt",
                [1, 2, 3],
                ["image_data"],
                None,
                [],
                [],
            )

            with patch.object(
                serving_chat, "_apply_conversation_template"
            ) as mock_conv:
                mock_conv.return_value = ("prompt", ["image_data"], None, [], [])

                (
                    prompt,
                    prompt_ids,
                    image_data,
                    audio_data,
                    modalities,
                    stop,
                    tool_call_constraint,
                ) = serving_chat._process_messages(request, True)

                assert image_data == ["image_data"]
                assert prompt == "prompt"

    def test_multimodal_request_with_audio(self, serving_chat):
        """Test request with audio content"""
        request = ChatCompletionRequest(
            model="test-model",
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Transcribe this audio"},
                        {
                            "type": "audio_url",
                            "audio_url": {"url": "data:audio/wav;base64,UklGR..."},
                        },
                    ],
                }
            ],
        )

        serving_chat.tokenizer_manager.model_config.is_multimodal = True

        with patch.object(serving_chat, "_apply_jinja_template") as mock_apply:
            mock_apply.return_value = (
                "prompt",
                [1, 2, 3],
                None,
                ["audio_data"],
                ["audio"],
                [],
            )

            with patch.object(
                serving_chat, "_apply_conversation_template"
            ) as mock_conv:
                mock_conv.return_value = ("prompt", None, ["audio_data"], ["audio"], [])

                (
                    prompt,
                    prompt_ids,
                    image_data,
                    audio_data,
                    modalities,
                    stop,
                    tool_call_constraint,
                ) = serving_chat._process_messages(request, True)

                assert audio_data == ["audio_data"]
                assert modalities == ["audio"]


class TestTemplateHandling:
    """Test chat template handling from adapter.py"""

    def test_jinja_template_processing(self, serving_chat):
        """Test Jinja template processing"""
        request = ChatCompletionRequest(
            model="test-model", messages=[{"role": "user", "content": "Hello"}]
        )

        # Mock the template attribute directly
        serving_chat.tokenizer_manager.chat_template_name = None
        serving_chat.tokenizer_manager.tokenizer.chat_template = "<jinja_template>"

        with patch.object(serving_chat, "_apply_jinja_template") as mock_apply:
            mock_apply.return_value = (
                "processed_prompt",
                [1, 2, 3],
                None,
                None,
                [],
                ["</s>"],
            )

            # Mock hasattr to simulate the None check
            with patch("builtins.hasattr") as mock_hasattr:
                mock_hasattr.return_value = True

                (
                    prompt,
                    prompt_ids,
                    image_data,
                    audio_data,
                    modalities,
                    stop,
                    tool_call_constraint,
                ) = serving_chat._process_messages(request, False)

                assert prompt == "processed_prompt"
                assert prompt_ids == [1, 2, 3]

    def test_conversation_template_processing(self, serving_chat):
        """Test conversation template processing"""
        request = ChatCompletionRequest(
            model="test-model", messages=[{"role": "user", "content": "Hello"}]
        )

        serving_chat.tokenizer_manager.chat_template_name = "llama-3"

        with patch.object(serving_chat, "_apply_conversation_template") as mock_apply:
            mock_apply.return_value = ("conv_prompt", None, None, [], ["</s>"])

            (
                prompt,
                prompt_ids,
                image_data,
                audio_data,
                modalities,
                stop,
                tool_call_constraint,
            ) = serving_chat._process_messages(request, False)

            assert prompt == "conv_prompt"
            assert stop == ["</s>"]

    def test_continue_final_message(self, serving_chat):
        """Test continue_final_message functionality"""
        request = ChatCompletionRequest(
            model="test-model",
            messages=[
                {"role": "user", "content": "Hello"},
                {"role": "assistant", "content": "Hi there"},
            ],
            continue_final_message=True,
        )

        with patch.object(serving_chat, "_apply_conversation_template") as mock_apply:
            mock_apply.return_value = ("Hi there", None, None, [], ["</s>"])

            (
                prompt,
                prompt_ids,
                image_data,
                audio_data,
                modalities,
                stop,
                tool_call_constraint,
            ) = serving_chat._process_messages(request, False)

            # Should handle continue_final_message properly
            assert prompt == "Hi there"


class TestReasoningContent:
    """Test reasoning content separation from adapter.py"""

    def test_reasoning_content_request(self, serving_chat):
        """Test request with reasoning content separation"""
        request = ChatCompletionRequest(
            model="test-model",
            messages=[{"role": "user", "content": "Solve this math problem"}],
            separate_reasoning=True,
            stream_reasoning=False,
        )

        with patch.object(serving_chat, "_process_messages") as mock_process:
            mock_process.return_value = (
                "Test prompt",
                [1, 2, 3],
                None,
                None,
                [],
                ["</s>"],
                None,  # tool_call_constraint
            )

            adapted_request, _ = serving_chat._convert_to_internal_request(
                [request], ["test-id"]
            )

            assert adapted_request.rid == "test-id"
            assert request.separate_reasoning == True

    def test_reasoning_content_response(self, serving_chat):
        """Test reasoning content in response"""
        mock_ret_item = {
            "text": "<thinking>This is reasoning</thinking>Answer: 42",
            "meta_info": {
                "output_token_logprobs": [],
                "output_top_logprobs": None,
            },
        }

        # Mock ReasoningParser
        with patch(
            "sglang.srt.entrypoints.openai.serving_chat.ReasoningParser"
        ) as mock_parser_class:
            mock_parser = Mock()
            mock_parser.parse_non_stream.return_value = (
                "This is reasoning",
                "Answer: 42",
            )
            mock_parser_class.return_value = mock_parser

            choice_logprobs = None
            reasoning_text = None
            text = mock_ret_item["text"]

            # Simulate reasoning processing
            enable_thinking = True
            if enable_thinking:
                parser = mock_parser_class(model_type="test", stream_reasoning=False)
                reasoning_text, text = parser.parse_non_stream(text)

            assert reasoning_text == "This is reasoning"
            assert text == "Answer: 42"


class TestSamplingParams:
    """Test sampling parameter handling from adapter.py"""

    def test_all_sampling_parameters(self, serving_chat):
        """Test all sampling parameters are properly handled"""
        request = ChatCompletionRequest(
            model="test-model",
            messages=[{"role": "user", "content": "Hello"}],
            temperature=0.8,
            max_tokens=150,
            max_completion_tokens=200,
            min_tokens=5,
            top_p=0.9,
            top_k=50,
            min_p=0.1,
            presence_penalty=0.1,
            frequency_penalty=0.2,
            repetition_penalty=1.1,
            stop=["<|endoftext|>"],
            stop_token_ids=[13, 14],
            regex=r"\d+",
            ebnf="<expr> ::= <number>",
            n=2,
            no_stop_trim=True,
            ignore_eos=True,
            skip_special_tokens=False,
            logit_bias={"1": 0.5, "2": -0.3},
        )

        with patch.object(serving_chat, "_process_messages") as mock_process:
            mock_process.return_value = (
                "Test prompt",
                [1, 2, 3],
                None,
                None,
                [],
                ["</s>"],
                None,  # tool_call_constraint
            )

            sampling_params = serving_chat._build_sampling_params(
                request, ["</s>"], None
            )

            # Verify all parameters
            assert sampling_params["temperature"] == 0.8
            assert sampling_params["max_new_tokens"] == 150
            assert sampling_params["min_new_tokens"] == 5
            assert sampling_params["top_p"] == 0.9
            assert sampling_params["top_k"] == 50
            assert sampling_params["min_p"] == 0.1
            assert sampling_params["presence_penalty"] == 0.1
            assert sampling_params["frequency_penalty"] == 0.2
            assert sampling_params["repetition_penalty"] == 1.1
            assert sampling_params["stop"] == ["</s>"]
            assert sampling_params["logit_bias"] == {"1": 0.5, "2": -0.3}

    def test_response_format_json_schema(self, serving_chat):
        """Test response format with JSON schema"""
        request = ChatCompletionRequest(
            model="test-model",
            messages=[{"role": "user", "content": "Generate JSON"}],
            response_format={
                "type": "json_schema",
                "json_schema": {
                    "name": "response",
                    "schema": {
                        "type": "object",
                        "properties": {"answer": {"type": "string"}},
                    },
                },
            },
        )

        with patch.object(serving_chat, "_process_messages") as mock_process:
            mock_process.return_value = (
                "Test prompt",
                [1, 2, 3],
                None,
                None,
                [],
                ["</s>"],
                None,  # tool_call_constraint
            )

            sampling_params = serving_chat._build_sampling_params(
                request, ["</s>"], None
            )

            assert "json_schema" in sampling_params
            assert '"type": "object"' in sampling_params["json_schema"]

    def test_response_format_json_object(self, serving_chat):
        """Test response format with JSON object"""
        request = ChatCompletionRequest(
            model="test-model",
            messages=[{"role": "user", "content": "Generate JSON"}],
            response_format={"type": "json_object"},
        )

        with patch.object(serving_chat, "_process_messages") as mock_process:
            mock_process.return_value = (
                "Test prompt",
                [1, 2, 3],
                None,
                None,
                [],
                ["</s>"],
                None,  # tool_call_constraint
            )

            sampling_params = serving_chat._build_sampling_params(
                request, ["</s>"], None
            )

            assert sampling_params["json_schema"] == '{"type": "object"}'