test_chat_utils.py 80.5 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
import warnings
5
from collections.abc import Mapping
6
from typing import Literal
7
8

import pytest
9
import torch
10

11
from vllm.assets.audio import AudioAsset
12
from vllm.assets.image import ImageAsset
13
from vllm.assets.video import VideoAsset
14
from vllm.config import ModelConfig
15
16
from vllm.entrypoints.chat_utils import (
    parse_chat_messages,
17
    parse_chat_messages_async,
18
)
19
from vllm.multimodal import MultiModalDataDict, MultiModalUUIDDict
20
from vllm.multimodal.utils import (
21
22
23
    encode_audio_url,
    encode_image_url,
    encode_video_url,
24
)
25
from vllm.utils.serial_utils import tensor2base64
26

27
KIMI_K2_5_MODEL_ID = "moonshotai/Kimi-K2.5"
28
PHI3V_MODEL_ID = "microsoft/Phi-3.5-vision-instruct"
29
QWEN2AUDIO_MODEL_ID = "Qwen/Qwen2-Audio-7B-Instruct"
30
QWEN25OMNI_MODEL_ID = "Qwen/Qwen2.5-Omni-7B"
31
MISTRAL_MODEL_ID = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
32
33


34
35
36
37
38
39
40
41
42
43
44
45
@pytest.fixture(scope="function")
def kimi_k2_5_model_config():
    return ModelConfig(
        KIMI_K2_5_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        limit_mm_per_prompt={
            "image": 2,
        },
    )


46
@pytest.fixture(scope="function")
47
def phi3v_model_config():
48
49
50
51
52
53
54
55
    return ModelConfig(
        PHI3V_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        limit_mm_per_prompt={
            "image": 2,
        },
    )
56
57


58
59
@pytest.fixture(scope="function")
def phi3v_model_config_mm_interleaved():
60
61
62
63
64
65
66
67
68
    return ModelConfig(
        PHI3V_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        interleave_mm_strings=True,
        limit_mm_per_prompt={
            "image": 2,
        },
    )
69
70


71
72
73
74
75
76
77
78
79
80
81
82
83
@pytest.fixture(scope="function")
def phi3v_model_config_image_embeds():
    return ModelConfig(
        PHI3V_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        limit_mm_per_prompt={
            "image": 2,
        },
        enable_mm_embeds=True,
    )


84
85
86
87
88
89
90
91
92
93
@pytest.fixture(scope="function")
def qwen25omni_model_config_image_embeds():
    return ModelConfig(
        QWEN25OMNI_MODEL_ID,
        runner="generate",
        limit_mm_per_prompt={"image": 2},
        enable_mm_embeds=True,
    )


94
95
96
97
98
99
100
101
102
103
104
105
@pytest.fixture(scope="function")
def qwen2_audio_model_config():
    return ModelConfig(
        QWEN2AUDIO_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        limit_mm_per_prompt={
            "audio": 1,
        },
    )


106
107
108
109
110
111
112
113
114
115
116
117
118
@pytest.fixture(scope="function")
def audio_embeds_model_config():
    return ModelConfig(
        QWEN2AUDIO_MODEL_ID,
        runner="generate",
        trust_remote_code=True,
        limit_mm_per_prompt={
            "audio": 2,
        },
        enable_mm_embeds=True,
    )


119
120
@pytest.fixture(scope="function")
def qwen25omni_model_config_mm_interleaved():
121
122
123
124
125
126
127
128
129
130
    return ModelConfig(
        QWEN25OMNI_MODEL_ID,
        runner="generate",
        interleave_mm_strings=True,
        limit_mm_per_prompt={
            "image": 2,
            "audio": 1,
            "video": 1,
        },
    )
131
132


133
134
@pytest.fixture(scope="function")
def mistral_model_config():
135
136
137
138
139
140
141
    return ModelConfig(
        MISTRAL_MODEL_ID,
        runner="generate",
        limit_mm_per_prompt={
            "image": 2,
        },
    )
142
143


144
145
@pytest.fixture(scope="module")
def image_url():
146
    image = ImageAsset("cherry_blossom")
147
    return encode_image_url(image.pil_image)
148
149


150
151
@pytest.fixture(scope="module")
def video_url():
152
    video = VideoAsset("baby_reading", 1)
153
    return encode_video_url(video.np_ndarrays)
154
155
156
157


@pytest.fixture(scope="module")
def audio_url():
158
    audio = AudioAsset("mary_had_lamb")
159
    return encode_audio_url(*audio.audio_and_sample_rate)
160
161


162
def _assert_mm_data_is_image_input(
163
    mm_data: MultiModalDataDict | None,
164
    image_count: int,
165
    skipped_image_indices: list | None = None,
166
167
168
169
170
171
172
) -> None:
    assert mm_data is not None
    assert set(mm_data.keys()) == {"image"}

    image_data = mm_data.get("image")
    assert image_data is not None

173
    assert isinstance(image_data, list) and len(image_data) == image_count
174
175
176
    if skipped_image_indices is not None:
        for i in skipped_image_indices:
            assert image_data[i] is None
177
178


179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def _assert_mm_data_is_vision_chunk_input(
    mm_data: MultiModalDataDict | None,
    vision_chunk_count: int,
) -> None:
    assert mm_data is not None
    assert set(mm_data.keys()) == {"vision_chunk"}

    vision_chunk_data = mm_data.get("vision_chunk")
    assert vision_chunk_data is not None

    assert (
        isinstance(vision_chunk_data, list)
        and len(vision_chunk_data) == vision_chunk_count
    )


195
def _assert_mm_uuids(
196
    mm_uuids: MultiModalUUIDDict | None,
197
    media_count: int,
198
    expected_uuids: list[str | None],
199
200
201
202
203
204
205
206
207
    modality: str = "image",
) -> None:
    if len(expected_uuids) > 0:
        assert mm_uuids is not None
        assert modality in mm_uuids

        image_uuids = mm_uuids.get(modality)
        assert image_uuids is not None

208
        assert isinstance(image_uuids, list) and len(image_uuids) == media_count
209
210
211
212
213
214

        assert image_uuids == expected_uuids
    else:
        assert mm_uuids is None


215
216
217
218
219
ModalityType = Literal["image", "video", "audio"]
MultiModalDataCounts = Mapping[ModalityType, int]


def _assert_mm_data_inputs(
220
    mm_data: MultiModalDataDict | None,
221
    data_count: MultiModalDataCounts,
222
    skipped_media_indices: dict[str, list] | None = None,  # modality -> list[int]
223
224
225
226
227
228
229
230
231
) -> None:
    assert mm_data is not None
    assert set(data_count.keys()) == (set(mm_data.keys()))

    for modality, n in data_count.items():
        modality_data = mm_data.get(modality)
        assert modality_data is not None
        assert isinstance(modality_data, list) and len(modality_data) == n

232
        if skipped_media_indices is not None:
233
            skipped_media_indices_for_modality = skipped_media_indices.get(modality)
234
235
236
237
            assert skipped_media_indices_for_modality is not None
            for i in skipped_media_indices_for_modality:
                assert modality_data[i] is None

238

239
240
241
242
def test_parse_chat_messages_single_image(
    phi3v_model_config,
    image_url,
):
243
    conversation, mm_data, mm_uuids = parse_chat_messages(
244
245
246
247
248
249
250
251
252
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
253
        phi3v_model_config,
254
255
        content_format="string",
    )
256

257
258
259
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
260
    _assert_mm_data_is_image_input(mm_data, 1)
261
262
263
264
265
266
267
268
269
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None])


def test_parse_chat_messages_single_image_with_uuid(
    phi3v_model_config,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
270
271
272
273
274
275
276
277
278
279
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url,
                        },
                        "uuid": image_uuid,
280
                    },
281
282
283
284
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
285
        phi3v_model_config,
286
287
288
        content_format="string",
    )

289
290
291
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
292
293
294
295
    _assert_mm_data_is_image_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])


296
297
298
299
300
301
def test_parse_chat_messages_single_empty_image_with_uuid(
    phi3v_model_config,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
302
303
304
305
306
307
308
309
310
311
312
313
314
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid,
                    },
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
315
        phi3v_model_config,
316
317
318
        content_format="string",
    )

319
320
321
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
322
323
324
325
    _assert_mm_data_is_image_input(mm_data, 1, skipped_image_indices=[0])
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])


326
327
328
329
330
331
def test_parse_chat_messages_single_image_with_bad_uuid_format(
    phi3v_model_config,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
332
333
334
335
336
337
338
339
340
341
342
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url,
                            "uuid": image_uuid,
                        },
                        "bad_uuid_key": image_uuid,
343
                    },
344
345
346
347
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
348
        phi3v_model_config,
349
350
351
        content_format="string",
    )

352
353
354
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
355
356
357
358
359
360
361
362
363
364
365
366
    _assert_mm_data_is_image_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None])


def test_parse_chat_messages_multiple_images_with_uuids(
    phi3v_model_config,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
367
368
369
370
371
372
373
374
375
376
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url,
                        },
                        "uuid": image_uuid1,
377
                    },
378
379
380
381
382
383
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url,
                        },
                        "uuid": image_uuid2,
384
                    },
385
386
387
388
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
389
        phi3v_model_config,
390
391
392
        content_format="string",
    )

393
394
395
396
397
398
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in the image?",
        }
    ]
399
400
401
402
    _assert_mm_data_is_image_input(mm_data, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


403
404
405
406
407
408
409
410
def test_parse_chat_messages_multiple_empty_images_with_uuids(
    phi3v_model_config,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid1,
                    },
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid2,
                    },
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
429
        phi3v_model_config,
430
431
432
        content_format="string",
    )

433
434
435
436
437
438
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in the image?",
        }
    ]
439
440
441
442
443
444
445
446
447
448
449
450
    _assert_mm_data_is_image_input(mm_data, 2, skipped_image_indices=[0, 1])
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


def test_parse_chat_messages_mixed_empty_images_with_uuids(
    phi3v_model_config,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
451
452
453
454
455
456
457
458
459
460
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url,
                        },
                        "uuid": image_uuid1,
461
                    },
462
463
464
465
466
467
468
469
470
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid2,
                    },
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
471
        phi3v_model_config,
472
473
474
        content_format="string",
    )

475
476
477
478
479
480
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in the image?",
        }
    ]
481
482
483
484
    _assert_mm_data_is_image_input(mm_data, 2, skipped_image_indices=[1])
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


485
486
487
488
489
490
@pytest.mark.asyncio
async def test_parse_chat_messages_single_image_with_uuid_async(
    phi3v_model_config,
    image_url,
):
    image_uuid = str(hash(image_url))
491
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
492
493
494
495
496
497
498
499
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {"url": image_url},
                        "uuid": image_uuid,
500
                    },
501
502
503
504
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
505
        phi3v_model_config,
506
507
508
        content_format="string",
    )

509
510
511
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
512
    _assert_mm_data_is_image_input(mm_data, 1)
513
514
515
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])


516
517
518
519
520
521
@pytest.mark.asyncio
async def test_parse_chat_messages_empty_image_with_uuid_async(
    phi3v_model_config,
    image_url,
):
    image_uuid = str(hash(image_url))
522
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
523
524
525
526
527
528
529
530
531
532
533
534
535
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid,
                    },
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
536
        phi3v_model_config,
537
538
539
        content_format="string",
    )

540
541
542
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
543
    _assert_mm_data_is_image_input(mm_data, 1, skipped_image_indices=[0])
544
545
546
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid])


547
548
549
550
551
552
553
554
@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_with_uuids_async(
    phi3v_model_config,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

555
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
556
557
558
559
560
561
562
563
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {"url": image_url},
                        "uuid": image_uuid1,
564
                    },
565
566
567
568
569
570
571
572
573
                    {
                        "type": "image_pil",
                        "image_pil": ImageAsset("cherry_blossom").pil_image,
                        "uuid": image_uuid2,
                    },
                    {"type": "text", "text": "What's in these images?"},
                ],
            }
        ],
574
        phi3v_model_config,
575
576
577
        content_format="string",
    )

578
579
580
581
582
583
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
584
    _assert_mm_data_is_image_input(mm_data, 2)
585
586
587
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


588
589
590
591
592
593
594
595
@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_empty_images_with_uuids_async(
    phi3v_model_config,
    image_url,
):
    image_uuid1 = "my_uuid_1"
    image_uuid2 = "my_uuid_2"

596
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": image_uuid1,
                    },
                    {
                        "type": "image_pil",
                        "image_pil": None,
                        "uuid": image_uuid2,
                    },
                    {"type": "text", "text": "What's in these images?"},
                ],
            }
        ],
615
        phi3v_model_config,
616
617
618
        content_format="string",
    )

619
620
621
622
623
624
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
625
    _assert_mm_data_is_image_input(mm_data, 2, skipped_image_indices=[0, 1])
626
627
628
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid1, image_uuid2])


629
630
631
632
633
634
635
@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_with_partial_uuids_async(
    phi3v_model_config,
    image_url,
):
    image_uuid2 = "my_uuid_2"

636
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
637
638
639
640
641
642
643
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {"url": image_url},
644
                    },
645
646
647
648
649
650
651
652
653
                    {
                        "type": "image_pil",
                        "image_pil": ImageAsset("cherry_blossom").pil_image,
                        "uuid": image_uuid2,
                    },
                    {"type": "text", "text": "What's in these images?"},
                ],
            }
        ],
654
        phi3v_model_config,
655
656
657
        content_format="string",
    )

658
659
660
661
662
663
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
664
    _assert_mm_data_is_image_input(mm_data, 2)
665
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, image_uuid2])
666
667


668
669
670
671
def test_parse_chat_messages_empty_system(
    mistral_model_config,
):
    # Test string format
672
    conversation, _, _ = parse_chat_messages(
673
        [
674
            {"role": "system", "content": ""},
675
676
            {
                "role": "user",
677
                "content": [{"type": "text", "text": "Who are you?"}],
678
679
            },
        ],
680
        mistral_model_config,
681
682
        content_format="string",
    )
683
    assert conversation == [
684
685
        {"role": "system", "content": ""},
        {"role": "user", "content": "Who are you?"},
686
    ]
687
688

    # Test openai format
689
    conversation, _, _ = parse_chat_messages(
690
        [
691
            {"role": "system", "content": ""},
692
693
            {
                "role": "user",
694
                "content": [{"type": "text", "text": "Who are you?"}],
695
696
            },
        ],
697
        mistral_model_config,
698
699
700
        content_format="openai",
    )
    assert conversation == [
701
702
        {"role": "system", "content": [{"type": "text", "text": ""}]},
        {"role": "user", "content": [{"type": "text", "text": "Who are you?"}]},
703
    ]
704
705


706
@pytest.mark.asyncio
707
708
709
710
async def test_parse_chat_messages_single_image_async(
    phi3v_model_config,
    image_url,
):
711
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
712
713
714
715
716
717
718
719
720
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "What's in the image?"},
                ],
            }
        ],
721
        phi3v_model_config,
722
723
        content_format="string",
    )
724

725
726
727
    assert conversation == [
        {"role": "user", "content": "<|image_1|>\nWhat's in the image?"}
    ]
728
    _assert_mm_data_is_image_input(mm_data, 1)
729
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None])
730
731
732
733
734
735


def test_parse_chat_messages_multiple_images(
    phi3v_model_config,
    image_url,
):
736
    conversation, mm_data, mm_uuids = parse_chat_messages(
737
738
739
740
741
742
743
744
745
746
747
748
749
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {
                        "type": "image_pil",
                        "image_pil": ImageAsset("cherry_blossom").pil_image,
                    },
                    {"type": "text", "text": "What's in these images?"},
                ],
            }
        ],
750
        phi3v_model_config,
751
752
        content_format="string",
    )
753

754
755
756
757
758
759
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
760
    _assert_mm_data_is_image_input(mm_data, 2)
761
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
762
763


764
765
766
767
768
def test_parse_chat_messages_empty_pil_image_with_uuid(
    phi3v_model_config,
):
    uuid = "abcd"
    conversation, mm_data, mm_uuids = parse_chat_messages(
769
770
771
772
773
774
775
776
777
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_pil", "image_pil": None, "uuid": uuid},
                    {"type": "text", "text": "What's in this image?"},
                ],
            }
        ],
778
        phi3v_model_config,
779
780
781
        content_format="string",
    )

782
783
784
785
786
787
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\nWhat's in this image?",
        }
    ]
788
789
790
791
792
    _assert_mm_data_is_image_input(mm_data, 1, skipped_image_indices=[0])
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[uuid])


def test_parse_chat_messages_empty_image_embeds_with_uuid(
793
    phi3v_model_config_image_embeds,
794
795
796
):
    uuid = "abcd"
    conversation, mm_data, mm_uuids = parse_chat_messages(
797
798
799
800
801
802
803
804
805
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_embeds", "image_embeds": None, "uuid": uuid},
                    {"type": "text", "text": "What's in this image?"},
                ],
            }
        ],
806
        phi3v_model_config_image_embeds,
807
808
809
        content_format="string",
    )

810
811
812
813
814
815
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\nWhat's in this image?",
        }
    ]
816

817
818
    assert mm_data is not None
    assert "image" in mm_data
819
820
821
822
    assert isinstance(mm_data["image"], list)
    assert len(mm_data["image"]) == 1
    assert mm_data["image"][0] is None

823
824
825
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[uuid])


826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
def test_parse_chat_messages_empty_audio_embeds_with_uuid(
    audio_embeds_model_config,
):
    """Test audio_embeds with UUID (no actual embeds data)."""
    uuid = "test-audio-uuid-123"

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Describe this audio"},
                    {"type": "audio_embeds", "audio_embeds": None, "uuid": uuid},
                ],
            }
        ],
842
        audio_embeds_model_config,
843
844
845
846
847
848
        content_format="string",
    )

    # Should have audio in mm_data as None (UUID provided)
    assert mm_data is not None
    assert "audio" in mm_data
849
850
851
852
    assert isinstance(mm_data["audio"], list)
    assert len(mm_data["audio"]) == 1
    assert mm_data["audio"][0] is None

853
854
855
856
857
858
859
860
861
862
863
864
    # UUID should be recorded
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[uuid])


def test_parse_chat_messages_audio_embeds_with_string(
    audio_embeds_model_config,
):
    """Test audio_embeds with base64 string embedding data."""

    import torch

    # Create a sample audio embedding tensor
865
866
    hidden_size = audio_embeds_model_config.get_inputs_embeds_size()
    audio_embedding = torch.randn(1, 128, hidden_size)
867
868

    # Encode it as base64
869
    base64_audio_embedding = tensor2base64(audio_embedding)
870
871
872
873
874
875
876
877
878
879
880
881
882
883

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Describe this audio"},
                    {
                        "type": "audio_embeds",
                        "audio_embeds": base64_audio_embedding,
                    },
                ],
            }
        ],
884
        audio_embeds_model_config,
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
        content_format="string",
    )

    # Should have audio embedding in mm_data (single tensor, not a list)
    assert mm_data is not None
    assert "audio" in mm_data
    assert isinstance(mm_data["audio"], torch.Tensor)
    assert mm_data["audio"].shape == audio_embedding.shape
    # No UUID provided
    assert mm_uuids is not None
    assert "audio" in mm_uuids
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[None])


@pytest.mark.asyncio
async def test_parse_chat_messages_audio_embeds_async(
    audio_embeds_model_config,
):
    """Test audio_embeds with async futures."""

    import torch

    # Create a sample audio embedding tensor
908
909
    hidden_size = audio_embeds_model_config.get_inputs_embeds_size()
    audio_embedding = torch.randn(1, 128, hidden_size)
910
911

    # Encode it as base64
912
    base64_audio_embedding = tensor2base64(audio_embedding)
913

914
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
915
916
917
918
919
920
921
922
923
924
925
926
        [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Describe this audio"},
                    {
                        "type": "audio_embeds",
                        "audio_embeds": base64_audio_embedding,
                    },
                ],
            }
        ],
927
        audio_embeds_model_config,
928
929
930
931
932
933
934
935
936
937
938
939
940
941
        content_format="string",
    )

    # Should have audio embedding in mm_data (single tensor, not a list)
    assert mm_data is not None
    assert "audio" in mm_data
    assert isinstance(mm_data["audio"], torch.Tensor)
    assert mm_data["audio"].shape == audio_embedding.shape
    # No UUID provided
    assert mm_uuids is not None
    assert "audio" in mm_uuids
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[None])


942
943
944
945
946
947
948
949
950
951
def test_parse_chat_messages_multiple_image_embeds(
    phi3v_model_config_image_embeds,
):
    """Test that multiple image_embeds in a single message are now supported.

    This test validates the fix for the limitation that previously only allowed
    one message with {'type': 'image_embeds'}. Now multiple image embeddings
    can be provided in a single request, similar to regular images.
    """
    # Create two sample image embedding tensors
952
953
954
    hidden_size = phi3v_model_config_image_embeds.get_inputs_embeds_size()
    image_embedding_1 = torch.randn(256, hidden_size)
    image_embedding_2 = torch.randn(128, hidden_size)
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066

    # Encode them as base64 using the convenience function
    base64_image_embedding_1 = tensor2base64(image_embedding_1)
    base64_image_embedding_2 = tensor2base64(image_embedding_2)

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_embeds",
                        "image_embeds": base64_image_embedding_1,
                    },
                    {
                        "type": "image_embeds",
                        "image_embeds": base64_image_embedding_2,
                    },
                    {"type": "text", "text": "Describe these two images."},
                ],
            }
        ],
        phi3v_model_config_image_embeds,
        content_format="string",
    )

    # Verify conversation structure
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nDescribe these two images.",
        }
    ]

    # Verify mm_data contains a list of embeddings (not a single embedding)
    assert mm_data is not None
    assert "image" in mm_data
    assert isinstance(mm_data["image"], list)
    assert len(mm_data["image"]) == 2

    # Verify each embedding has the correct shape
    assert isinstance(mm_data["image"][0], torch.Tensor)
    assert mm_data["image"][0].shape == image_embedding_1.shape
    assert isinstance(mm_data["image"][1], torch.Tensor)
    assert mm_data["image"][1].shape == image_embedding_2.shape

    # Verify UUIDs (None since we didn't provide any)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])


def test_parse_chat_messages_multiple_image_embeds_with_uuids(
    phi3v_model_config_image_embeds,
):
    """Test multiple image_embeds with UUIDs.

    This validates that UUIDs are properly tracked for multiple embeddings.
    """
    uuid1 = "image-uuid-1"
    uuid2 = "image-uuid-2"

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_embeds",
                        "image_embeds": None,
                        "uuid": uuid1,
                    },
                    {
                        "type": "image_embeds",
                        "image_embeds": None,
                        "uuid": uuid2,
                    },
                    {"type": "text", "text": "Compare these images."},
                ],
            }
        ],
        phi3v_model_config_image_embeds,
        content_format="string",
    )

    # Verify conversation structure
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nCompare these images.",
        }
    ]

    # Verify mm_data contains a list with None values (UUID references)
    assert mm_data is not None
    assert "image" in mm_data
    assert isinstance(mm_data["image"], list)
    assert len(mm_data["image"]) == 2
    assert mm_data["image"][0] is None
    assert mm_data["image"][1] is None

    # Verify UUIDs are correctly tracked
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[uuid1, uuid2])


@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_image_embeds_async(
    phi3v_model_config_image_embeds,
):
    """Test multiple image_embeds with async parsing.

    This validates the AsyncMultiModalItemTracker also supports multiple embeddings.
    """
    # Create two sample image embedding tensors
1067
1068
1069
    hidden_size = phi3v_model_config_image_embeds.get_inputs_embeds_size()
    image_embedding_1 = torch.randn(200, hidden_size)
    image_embedding_2 = torch.randn(150, hidden_size)
1070
1071
1072
1073
1074

    # Encode them as base64 using the convenience function
    base64_image_embedding_1 = tensor2base64(image_embedding_1)
    base64_image_embedding_2 = tensor2base64(image_embedding_2)

1075
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_embeds",
                        "image_embeds": base64_image_embedding_1,
                    },
                    {
                        "type": "image_embeds",
                        "image_embeds": base64_image_embedding_2,
                    },
                    {"type": "text", "text": "What do these images show?"},
                ],
            }
        ],
        phi3v_model_config_image_embeds,
        content_format="string",
    )

    # Verify conversation structure
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat do these images show?",
        }
    ]

    # Await the future and verify mm_data
    assert mm_data is not None
    assert "image" in mm_data
    assert isinstance(mm_data["image"], list)
    assert len(mm_data["image"]) == 2

    # Verify each embedding has the correct shape
    assert isinstance(mm_data["image"][0], torch.Tensor)
    assert mm_data["image"][0].shape == image_embedding_1.shape
    assert isinstance(mm_data["image"][1], torch.Tensor)
    assert mm_data["image"][1].shape == image_embedding_2.shape

    # Verify UUIDs
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])


1120
1121
@pytest.mark.asyncio
async def test_parse_chat_messages_empty_image_embeds_with_uuid_async(
1122
    phi3v_model_config_image_embeds,
1123
1124
):
    uuid = "abcd"
1125
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1126
1127
1128
1129
1130
1131
1132
1133
1134
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_embeds", "image_embeds": None, "uuid": uuid},
                    {"type": "text", "text": "What's in this image?"},
                ],
            }
        ],
1135
        phi3v_model_config_image_embeds,
1136
1137
1138
        content_format="string",
    )

1139
1140
1141
1142
1143
1144
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\nWhat's in this image?",
        }
    ]
1145
1146
    assert mm_data is not None
    assert "image" in mm_data
1147
1148
1149
1150
    assert isinstance(mm_data["image"], list)
    assert len(mm_data["image"]) == 1
    assert mm_data["image"][0] is None

1151
1152
1153
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[uuid])


1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
def test_parse_chat_messages_empty_dict_image_embeds(
    phi3v_model_config_image_embeds,
):
    """Test that empty dictionary for image_embeds is handled without errors."""
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_embeds", "image_embeds": {}},
                    {"type": "text", "text": "What's in this image?"},
                ],
            }
        ],
        phi3v_model_config_image_embeds,
        content_format="string",
    )

    # Verify conversation structure
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\nWhat's in this image?",
        }
    ]

    # Verify mm_data contains an empty dictionary of embeddings
    assert mm_data is not None
    assert "image" in mm_data
    assert isinstance(mm_data["image"], dict)
    assert len(mm_data["image"]) == 0

    # Verify UUIDs (None since we didn't provide any)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None])


def test_parse_chat_messages_multiple_dict_image_embeds(
1191
    qwen25omni_model_config_image_embeds,
1192
1193
1194
1195
):
    """Test that multiple dictionaries for image_embeds is handled without errors."""
    # Create two sample image embedding tensors
    batch_size = 2
1196
1197
1198
    hidden_size = qwen25omni_model_config_image_embeds.get_inputs_embeds_size()
    image_embeds = torch.randn(batch_size * 220, hidden_size)
    image_grid_thw = torch.tensor([[1, 22, 40] for _ in range(batch_size)])
1199
1200
1201
1202
1203
1204
1205
1206
1207

    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_embeds",
                        "image_embeds": {
1208
1209
                            "image_embeds": tensor2base64(embeds),
                            "image_grid_thw": tensor2base64(grid_thw),
1210
1211
                        },
                    }
1212
1213
1214
                    for embeds, grid_thw in zip(
                        image_embeds.chunk(batch_size), image_grid_thw
                    )
1215
1216
1217
1218
1219
1220
                ]
                + [
                    {"type": "text", "text": "Describe these two images."},
                ],
            }
        ],
1221
        qwen25omni_model_config_image_embeds,
1222
1223
1224
1225
1226
1227
1228
        content_format="string",
    )

    # Verify conversation structure
    assert conversation == [
        {
            "role": "user",
1229
1230
            "content": "<|vision_start|><|IMAGE|><|vision_end|>\n"
            "<|vision_start|><|IMAGE|><|vision_end|>\nDescribe these two images.",
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
        }
    ]

    # Verify mm_data contains a dictionary of multi-embeddings
    assert mm_data is not None
    assert "image" in mm_data
    assert isinstance(mm_data["image"], dict)
    assert len(mm_data["image"]) == batch_size

    # Verify each embedding has the correct shape
1241
1242
1243
1244
    assert isinstance(mm_data["image"]["image_embeds"], torch.Tensor)
    assert mm_data["image"]["image_embeds"].shape == image_embeds.shape
    assert isinstance(mm_data["image"]["image_grid_thw"], torch.Tensor)
    assert mm_data["image"]["image_grid_thw"].shape == image_grid_thw.shape
1245
1246
1247
1248
1249

    # Verify UUIDs (None since we didn't provide any)
    _assert_mm_uuids(mm_uuids, batch_size, expected_uuids=[None, None])


1250
@pytest.mark.asyncio
1251
1252
1253
1254
async def test_parse_chat_messages_multiple_images_async(
    phi3v_model_config,
    image_url,
):
1255
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {
                        "type": "image_pil",
                        "image_pil": ImageAsset("cherry_blossom").pil_image,
                    },
                    {"type": "text", "text": "What's in these images?"},
                ],
            }
        ],
1269
        phi3v_model_config,
1270
1271
        content_format="string",
    )
1272

1273
1274
1275
1276
1277
1278
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
1279
    _assert_mm_data_is_image_input(mm_data, 2)
1280
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1281
1282
1283
1284
1285
1286


def test_parse_chat_messages_placeholder_already_in_prompt(
    phi3v_model_config,
    image_url,
):
1287
    conversation, mm_data, mm_uuids = parse_chat_messages(
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {
                        "type": "text",
                        "text": "What's in <|image_1|> and how does it compare to <|image_2|>?",  # noqa: E501
                    },
                ],
            }
        ],
1301
        phi3v_model_config,
1302
1303
        content_format="string",
    )
1304
1305
1306
1307
1308
1309
    assert conversation == [
        {
            "role": "user",
            "content": "What's in <|image_1|> and how does it compare to <|image_2|>?",
        }
    ]
1310
    _assert_mm_data_is_image_input(mm_data, 2)
1311
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1312
1313


1314
1315
1316
1317
def test_parse_chat_messages_placeholder_one_already_in_prompt(
    phi3v_model_config,
    image_url,
):
1318
    conversation, mm_data, mm_uuids = parse_chat_messages(
1319
1320
1321
1322
1323
1324
1325
1326
        [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {
                        "type": "text",
1327
1328
                        "text": "What's in <|image_1|> and how does it compare to "
                        "the other one?",
1329
1330
1331
1332
                    },
                ],
            }
        ],
1333
        phi3v_model_config,
1334
1335
        content_format="string",
    )
1336

1337
1338
1339
    assert conversation == [
        {
            "role": "user",
1340
1341
            "content": "<|image_2|>\nWhat's in <|image_1|> and how does it compare to "
            "the other one?",
1342
1343
        }
    ]
1344
    _assert_mm_data_is_image_input(mm_data, 2)
1345
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1346
1347


1348
1349
1350
1351
def test_parse_chat_messages_multiple_images_across_messages(
    phi3v_model_config,
    image_url,
):
1352
    conversation, mm_data, mm_uuids = parse_chat_messages(
1353
1354
        [
            {
1355
                "role": "user",
1356
                "content": [
1357
1358
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "What's in this image?"},
1359
1360
                ],
            },
1361
            {"role": "assistant", "content": "Some stuff."},
1362
            {
1363
                "role": "user",
1364
                "content": [
1365
1366
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "What about this one?"},
1367
1368
1369
                ],
            },
        ],
1370
        phi3v_model_config,
1371
1372
        content_format="string",
    )
1373
1374

    assert conversation == [
1375
1376
1377
        {"role": "user", "content": "<|image_1|>\nWhat's in this image?"},
        {"role": "assistant", "content": "Some stuff."},
        {"role": "user", "content": "<|image_2|>\nWhat about this one?"},
1378
    ]
1379
    _assert_mm_data_is_image_input(mm_data, 2)
1380
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1381
1382


1383
def test_parse_chat_messages_multiple_images_with_uuids_across_messages(
1384
    phi3v_model_config,
1385
    image_url,
1386
):
1387
1388
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
1389
1390
        [
            {
1391
                "role": "user",
1392
1393
1394
                "content": [
                    {
                        "type": "image_url",
1395
                        "image_url": {"url": image_url},
1396
1397
                        "uuid": image_uuid,
                    },
1398
                    {"type": "text", "text": "What's in this image?"},
1399
                ],
1400
            },
1401
            {"role": "assistant", "content": "Some stuff."},
1402
            {
1403
                "role": "user",
1404
1405
1406
                "content": [
                    {
                        "type": "image_url",
1407
                        "image_url": {"url": image_url},
1408
1409
                        "uuid": image_uuid,
                    },
1410
                    {"type": "text", "text": "What about this one?"},
1411
1412
1413
                ],
            },
        ],
1414
        phi3v_model_config,
1415
1416
1417
1418
        content_format="string",
    )

    assert conversation == [
1419
1420
1421
        {"role": "user", "content": "<|image_1|>\nWhat's in this image?"},
        {"role": "assistant", "content": "Some stuff."},
        {"role": "user", "content": "<|image_2|>\nWhat about this one?"},
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
    ]
    _assert_mm_data_is_image_input(mm_data, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid, image_uuid])


def test_parse_chat_messages_context_text_format(
    phi3v_model_config,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
                "role": "user",
1434
                "content": [{"type": "text", "text": "What's in this text?"}],
1435
            },
1436
1437
            {"role": "assistant", "content": "Some stuff."},
            {"role": "user", "content": "What about this one?"},
1438
        ],
1439
        phi3v_model_config,
1440
1441
        content_format="openai",
    )
1442
1443
1444
1445

    assert conversation == [
        {
            "role": "user",
1446
            "content": [{"type": "text", "text": "What's in this text?"}],
1447
1448
1449
        },
        {
            "role": "assistant",
1450
            "content": [{"type": "text", "text": "Some stuff."}],
1451
1452
1453
        },
        {
            "role": "user",
1454
            "content": [{"type": "text", "text": "What about this one?"}],
1455
1456
        },
    ]
1457
1458
    assert mm_data is None
    assert mm_uuids is None
1459
1460


1461
1462
1463
1464
def test_parse_chat_messages_rejects_too_many_images_in_one_message(
    phi3v_model_config,
    image_url,
):
1465
1466
1467
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore",
1468
1469
            message="coroutine 'async_get_and_parse_image' was never awaited",
        )
1470
        with pytest.raises(ValueError, match="At most"):
1471
            parse_chat_messages(
1472
1473
1474
1475
1476
1477
1478
                [
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "image_url",
                                "image_url": {"url": image_url},
1479
                            },
1480
1481
1482
                            {
                                "type": "image_url",
                                "image_url": {"url": image_url},
1483
                            },
1484
1485
1486
                            {
                                "type": "image_url",
                                "image_url": {"url": image_url},
1487
                            },
1488
1489
1490
1491
                            {"type": "text", "text": "What's in these images?"},
                        ],
                    }
                ],
1492
                phi3v_model_config,
1493
1494
                content_format="string",
            )
1495
1496


1497
1498
1499
1500
def test_parse_chat_messages_rejects_too_many_images_across_messages(
    phi3v_model_config,
    image_url,
):
1501
1502
1503
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore",
1504
1505
            message="coroutine 'async_get_and_parse_image' was never awaited",
        )
1506
        with pytest.raises(ValueError, match="At most"):
1507
            parse_chat_messages(
1508
1509
                [
                    {
1510
                        "role": "user",
1511
1512
1513
                        "content": [
                            {
                                "type": "image_url",
1514
                                "image_url": {"url": image_url},
1515
                            },
1516
                            {"type": "text", "text": "What's in this image?"},
1517
1518
                        ],
                    },
1519
                    {"role": "assistant", "content": "Some stuff."},
1520
                    {
1521
                        "role": "user",
1522
1523
1524
                        "content": [
                            {
                                "type": "image_url",
1525
                                "image_url": {"url": image_url},
1526
1527
1528
                            },
                            {
                                "type": "image_url",
1529
                                "image_url": {"url": image_url},
1530
                            },
1531
                            {"type": "text", "text": "What about these two?"},
1532
1533
1534
                        ],
                    },
                ],
1535
                phi3v_model_config,
1536
1537
                content_format="string",
            )
1538
1539
1540
1541
1542
1543


def test_parse_chat_messages_multiple_images_uncommon_input(
    phi3v_model_config,
    image_url,
):
1544
    conversation, mm_data, mm_uuids = parse_chat_messages(
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
        [
            {
                "role": "user",
                "content": [
                    "What's in these images?",
                    {"image_url": image_url},
                    {"image_url": image_url},
                ],
            }
        ],
1555
        phi3v_model_config,
1556
1557
        content_format="string",
    )
1558

1559
1560
1561
1562
1563
1564
    assert conversation == [
        {
            "role": "user",
            "content": "<|image_1|>\n<|image_2|>\nWhat's in these images?",
        }
    ]
1565
    _assert_mm_data_is_image_input(mm_data, 2)
1566
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1567
1568


1569
1570
1571
1572
def test_parse_chat_messages_multiple_images_interleave(
    phi3v_model_config_mm_interleaved,
    image_url,
):
1573
    conversation, mm_data, mm_uuids = parse_chat_messages(
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "I need you to compare this image",
                    },
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "and this one"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "Do they have differences?"},
                ],
            }
        ],
1589
        phi3v_model_config_mm_interleaved,
1590
1591
1592
        content_format="string",
    )

1593
1594
1595
1596
1597
1598
1599
    assert conversation == [
        {
            "role": "user",
            "content": "I need you to compare this image\n<|image_1|>\nand this one\n<|image_2|>\n"  # noqa: E501
            "Do they have differences?",
        }
    ]
1600
    _assert_mm_data_is_image_input(mm_data, 2)
1601
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])
1602
1603
1604
1605
1606
1607
1608


@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_interleave_async(
    phi3v_model_config_mm_interleaved,
    image_url,
):
1609
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "I need you to compare this image",
                    },
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "and this one"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "Do they have differences?"},
                ],
            }
        ],
1625
        phi3v_model_config_mm_interleaved,
1626
1627
1628
        content_format="string",
    )

1629
1630
1631
1632
1633
1634
1635
    assert conversation == [
        {
            "role": "user",
            "content": "I need you to compare this image\n<|image_1|>\nand this one\n<|image_2|>\n"  # noqa: E501
            "Do they have differences?",
        }
    ]
1636
    _assert_mm_data_is_image_input(mm_data, 2)
1637
1638
1639
1640
1641
1642
1643
1644
1645
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])


@pytest.mark.asyncio
async def test_parse_chat_messages_multiple_images_with_uuids_interleave_async(
    phi3v_model_config_mm_interleaved,
    image_url,
):
    image_uuid = str(hash(image_url))
1646
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
1647
1648
1649
1650
1651
1652
1653
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "I need you to compare this image",
1654
                    },
1655
1656
1657
1658
                    {
                        "type": "image_url",
                        "image_url": {"url": image_url},
                        "uuid": image_uuid,
1659
                    },
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
                    {"type": "text", "text": "and this one"},
                    {
                        "type": "image_url",
                        "image_url": {"url": image_url},
                        "uuid": image_uuid,
                    },
                    {"type": "text", "text": "Do they have differences?"},
                ],
            }
        ],
1670
        phi3v_model_config_mm_interleaved,
1671
1672
1673
        content_format="string",
    )

1674
1675
1676
1677
1678
1679
1680
    assert conversation == [
        {
            "role": "user",
            "content": "I need you to compare this image\n<|image_1|>\nand this one\n<|image_2|>\n"  # noqa: E501
            "Do they have differences?",
        }
    ]
1681
    _assert_mm_data_is_image_input(mm_data, 2)
1682
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid, image_uuid])
1683
1684
1685
1686
1687
1688


def test_parse_chat_messages_multiple_images_multiple_messages_interleave(
    phi3v_model_config_mm_interleaved,
    image_url,
):
1689
    conversation, mm_data, mm_uuids = parse_chat_messages(
1690
1691
        [
            {
1692
                "role": "user",
1693
                "content": [
1694
1695
1696
                    {"type": "text", "text": "What's on this image?"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "Be accurate."},
1697
1698
                ],
            },
1699
            {"role": "assistant", "content": "Some stuff."},
1700
            {
1701
                "role": "user",
1702
                "content": [
1703
1704
                    {"type": "text", "text": "What's on this image?"},
                    {"type": "image_url", "image_url": {"url": image_url}},
1705
1706
1707
                ],
            },
        ],
1708
        phi3v_model_config_mm_interleaved,
1709
1710
1711
        content_format="string",
    )

1712
1713
1714
1715
1716
    assert conversation == [
        {
            "role": "user",
            "content": "What's on this image?\n<|image_1|>\nBe accurate.",
        },
1717
1718
        {"role": "assistant", "content": "Some stuff."},
        {"role": "user", "content": "What's on this image?\n<|image_2|>"},
1719
    ]
1720
    _assert_mm_data_is_image_input(mm_data, 2)
1721
1722
1723
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None])


1724
def test_parse_chat_messages_multiple_images_with_uuids_multiple_messages_interleave(
1725
1726
1727
1728
1729
1730
1731
    phi3v_model_config_mm_interleaved,
    image_url,
):
    image_uuid = str(hash(image_url))
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
1732
                "role": "user",
1733
                "content": [
1734
                    {"type": "text", "text": "What's on this image?"},
1735
1736
                    {
                        "type": "image_url",
1737
                        "image_url": {"url": image_url},
1738
1739
                        "uuid": image_uuid,
                    },
1740
                    {"type": "text", "text": "Be accurate."},
1741
1742
                ],
            },
1743
            {"role": "assistant", "content": "Some stuff."},
1744
            {
1745
                "role": "user",
1746
                "content": [
1747
                    {"type": "text", "text": "What's on this image?"},
1748
1749
                    {
                        "type": "image_url",
1750
                        "image_url": {"url": image_url},
1751
1752
1753
1754
1755
                        "uuid": image_uuid,
                    },
                ],
            },
        ],
1756
        phi3v_model_config_mm_interleaved,
1757
1758
1759
1760
1761
1762
1763
1764
        content_format="string",
    )

    assert conversation == [
        {
            "role": "user",
            "content": "What's on this image?\n<|image_1|>\nBe accurate.",
        },
1765
1766
        {"role": "assistant", "content": "Some stuff."},
        {"role": "user", "content": "What's on this image?\n<|image_2|>"},
1767
1768
1769
    ]
    _assert_mm_data_is_image_input(mm_data, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[image_uuid, image_uuid])
1770
1771
1772


def test_parse_chat_messages_multiple_modals_multiple_messages_interleave(
1773
1774
1775
1776
1777
    qwen25omni_model_config_mm_interleaved,
    image_url,
    video_url,
    audio_url,
):
1778
    conversation, mm_data, mm_uuids = parse_chat_messages(
1779
1780
        [
            {
1781
                "role": "user",
1782
                "content": [
1783
1784
1785
1786
                    {"type": "text", "text": "What's on this image?"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "Now listen to this audio"},
                    {"type": "audio_url", "audio_url": {"url": audio_url}},
1787
1788
                ],
            },
1789
            {"role": "assistant", "content": "Some stuff."},
1790
            {
1791
                "role": "user",
1792
                "content": [
1793
1794
1795
1796
                    {"type": "text", "text": "What's on this image?"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "And what's in the video?"},
                    {"type": "video_url", "video_url": {"url": video_url}},
1797
1798
1799
                ],
            },
        ],
1800
        qwen25omni_model_config_mm_interleaved,
1801
1802
1803
1804
1805
        content_format="string",
    )

    assert conversation == [
        {
1806
            "role": "user",
1807
1808
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nNow listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",
1809
        },
1810
        {"role": "assistant", "content": "Some stuff."},
1811
        {
1812
            "role": "user",
1813
1814
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nAnd what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
1815
1816
        },
    ]
1817
1818

    _assert_mm_data_inputs(mm_data, {"image": 2, "video": 1, "audio": 1})
1819
    _assert_mm_uuids(mm_uuids, 2, modality="image", expected_uuids=[None, None])
1820
1821
1822
1823
    _assert_mm_uuids(mm_uuids, 1, modality="video", expected_uuids=[None])
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[None])


1824
def test_parse_chat_messages_multiple_modals_with_uuids_multiple_messages_interleave(
1825
1826
1827
1828
1829
1830
1831
1832
    qwen25omni_model_config_mm_interleaved,
    image_url,
    video_url,
    audio_url,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
1833
                "role": "user",
1834
                "content": [
1835
                    {"type": "text", "text": "What's on this image?"},
1836
1837
                    {
                        "type": "image_url",
1838
                        "image_url": {"url": image_url},
1839
1840
                        "uuid": "image_123",
                    },
1841
                    {"type": "text", "text": "Now listen to this audio"},
1842
1843
                    {
                        "type": "audio_url",
1844
                        "audio_url": {"url": audio_url},
1845
1846
1847
1848
                        "uuid": "audio_123",
                    },
                ],
            },
1849
            {"role": "assistant", "content": "Some stuff."},
1850
            {
1851
                "role": "user",
1852
                "content": [
1853
                    {"type": "text", "text": "What's on this image?"},
1854
1855
                    {
                        "type": "image_url",
1856
                        "image_url": {"url": image_url},
1857
1858
                        "uuid": "image_123",
                    },
1859
                    {"type": "text", "text": "And what's in the video?"},
1860
1861
                    {
                        "type": "video_url",
1862
                        "video_url": {"url": video_url},
1863
1864
1865
1866
1867
                        "uuid": "video_123",
                    },
                ],
            },
        ],
1868
        qwen25omni_model_config_mm_interleaved,
1869
1870
1871
1872
1873
        content_format="string",
    )

    assert conversation == [
        {
1874
            "role": "user",
1875
1876
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nNow listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",
1877
        },
1878
        {"role": "assistant", "content": "Some stuff."},
1879
        {
1880
            "role": "user",
1881
1882
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nAnd what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
1883
1884
1885
1886
        },
    ]

    _assert_mm_data_inputs(mm_data, {"image": 2, "video": 1, "audio": 1})
1887
1888
1889
1890
1891
    _assert_mm_uuids(
        mm_uuids, 2, modality="image", expected_uuids=["image_123", "image_123"]
    )
    _assert_mm_uuids(mm_uuids, 1, modality="video", expected_uuids=["video_123"])
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=["audio_123"])
1892
1893


1894
1895
1896
1897
1898
1899
1900
1901
1902
def test_parse_chat_messages_multiple_modals_with_uuids_multiple_empty_media_messages_interleave(  # noqa: E501
    qwen25omni_model_config_mm_interleaved,
    image_url,
    video_url,
    audio_url,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
1903
                "role": "user",
1904
                "content": [
1905
                    {"type": "text", "text": "What's on this image?"},
1906
1907
1908
1909
1910
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": "image_123",
                    },
1911
                    {"type": "text", "text": "Now listen to this audio"},
1912
1913
1914
1915
1916
1917
1918
                    {
                        "type": "audio_url",
                        "audio_url": None,
                        "uuid": "audio_123",
                    },
                ],
            },
1919
            {"role": "assistant", "content": "Some stuff."},
1920
            {
1921
                "role": "user",
1922
                "content": [
1923
                    {"type": "text", "text": "What's on this image?"},
1924
1925
1926
1927
1928
                    {
                        "type": "image_url",
                        "image_url": None,
                        "uuid": "image_123",
                    },
1929
                    {"type": "text", "text": "And what's in the video?"},
1930
1931
1932
1933
1934
1935
1936
1937
                    {
                        "type": "video_url",
                        "video_url": None,
                        "uuid": "video_123",
                    },
                ],
            },
        ],
1938
        qwen25omni_model_config_mm_interleaved,
1939
1940
1941
1942
1943
        content_format="string",
    )

    assert conversation == [
        {
1944
            "role": "user",
1945
1946
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nNow listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",
1947
        },
1948
        {"role": "assistant", "content": "Some stuff."},
1949
        {
1950
            "role": "user",
1951
1952
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nAnd what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
1953
1954
1955
        },
    ]

1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
    _assert_mm_data_inputs(
        mm_data,
        {"image": 2, "video": 1, "audio": 1},
        skipped_media_indices={"image": [0, 1], "video": [0], "audio": [0]},
    )
    _assert_mm_uuids(
        mm_uuids, 2, modality="image", expected_uuids=["image_123", "image_123"]
    )
    _assert_mm_uuids(mm_uuids, 1, modality="video", expected_uuids=["video_123"])
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=["audio_123"])
1966
1967


1968
1969
1970
1971
1972
1973
1974
1975
1976
def test_parse_chat_messages_multiple_modals_with_partial_uuids_multiple_messages_interleave(  # noqa: E501
    qwen25omni_model_config_mm_interleaved,
    image_url,
    video_url,
    audio_url,
):
    conversation, mm_data, mm_uuids = parse_chat_messages(
        [
            {
1977
                "role": "user",
1978
                "content": [
1979
                    {"type": "text", "text": "What's on this image?"},
1980
1981
                    {
                        "type": "image_url",
1982
                        "image_url": {"url": image_url},
1983
1984
                        "uuid": "image_123",
                    },
1985
1986
                    {"type": "text", "text": "Now listen to this audio"},
                    {"type": "audio_url", "audio_url": {"url": audio_url}},
1987
1988
                ],
            },
1989
            {"role": "assistant", "content": "Some stuff."},
1990
            {
1991
                "role": "user",
1992
                "content": [
1993
1994
1995
                    {"type": "text", "text": "What's on this image?"},
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": "And what's in the video?"},
1996
1997
                    {
                        "type": "video_url",
1998
                        "video_url": {"url": video_url},
1999
2000
2001
2002
2003
                        "uuid": "video_123",
                    },
                ],
            },
        ],
2004
        qwen25omni_model_config_mm_interleaved,
2005
2006
2007
2008
2009
        content_format="string",
    )

    assert conversation == [
        {
2010
            "role": "user",
2011
2012
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nNow listen to this audio\nAudio 1: <|audio_bos|><|AUDIO|><|audio_eos|>",
2013
        },
2014
        {"role": "assistant", "content": "Some stuff."},
2015
        {
2016
            "role": "user",
2017
2018
            "content": "What's on this image?\n<|vision_start|><|IMAGE|><|vision_end|>"
            "\nAnd what's in the video?\n<|vision_start|><|VIDEO|><|vision_end|>",
2019
2020
2021
2022
        },
    ]

    _assert_mm_data_inputs(mm_data, {"image": 2, "video": 1, "audio": 1})
2023
2024
    _assert_mm_uuids(mm_uuids, 2, modality="image", expected_uuids=["image_123", None])
    _assert_mm_uuids(mm_uuids, 1, modality="video", expected_uuids=["video_123"])
2025
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[None])
2026
2027
2028
2029
2030
2031
2032


def test_parse_chat_messages_multiple_images_interleave_with_placeholders(
    phi3v_model_config_mm_interleaved,
    image_url,
):
    with pytest.raises(
2033
2034
2035
        ValueError,
        match=r"Found more '<|image_1|>' placeholders in input prompt "
        "than actual multimodal data items.",
2036
    ):
2037
        parse_chat_messages(
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
            [
                {
                    "role": "user",
                    "content": [
                        {"type": "image_url", "image_url": {"url": image_url}},
                        {"type": "image_url", "image_url": {"url": image_url}},
                        {
                            "type": "text",
                            "text": "I need you to compare this image\n<|image_1|>\nand this one\n<|image_2|>\n"  # noqa: E501
                            "Do they have differences?",
                        },
                    ],
                }
            ],
2052
            phi3v_model_config_mm_interleaved,
2053
2054
2055
2056
            content_format="string",
        )


2057
def test_parse_chat_messages_include_thinking_chunk(mistral_model_config):
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
    messages = [
        {
            "role": "system",
            "content": [
                {"type": "text", "text": "You are a helpful assistant."},
                {
                    "type": "thinking",
                    "closed": True,
                    "thinking": "Only return the answer when you are confident.",
                },
            ],
        },
        {"role": "user", "content": "What is 2+2?"},
        {
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Let me think about it."},
                {"type": "thinking", "closed": True, "thinking": "2+2 = 4"},
                {
                    "type": "text",
                    "text": "The answer is 4.",
                },
            ],
        },
    ]
Julien Denize's avatar
Julien Denize committed
2083

2084
    conversation_with_thinking, _, _ = parse_chat_messages(
Julien Denize's avatar
Julien Denize committed
2085
        messages,
2086
        mistral_model_config,
Julien Denize's avatar
Julien Denize committed
2087
2088
2089
        content_format="openai",
    )

2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
    expected_conversation = [
        {
            "role": "system",
            "content": [
                {"type": "text", "text": "You are a helpful assistant."},
                {
                    "type": "text",
                    "text": "Only return the answer when you are confident.",
                },
            ],
        },
        {
            "role": "user",
            "content": [{"type": "text", "text": "What is 2+2?"}],
        },
        {
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Let me think about it."},
                {"type": "text", "text": "2+2 = 4"},
                {"type": "text", "text": "The answer is 4."},
            ],
        },
    ]
Julien Denize's avatar
Julien Denize committed
2114
2115
2116
2117

    assert conversation_with_thinking == expected_conversation


2118
2119
2120
2121
2122
def test_parse_chat_messages_single_empty_audio_with_uuid(
    qwen2_audio_model_config,
):
    audio_uuid = "abcd"
    conversation, mm_data, mm_uuids = parse_chat_messages(
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "input_audio",
                        "input_audio": {},
                        "uuid": audio_uuid,
                    },
                    {"type": "text", "text": "What does the audio say?"},
                ],
            }
        ],
2136
        qwen2_audio_model_config,
2137
2138
2139
        content_format="string",
    )

2140
2141
2142
    assert conversation == [
        {
            "role": "user",
2143
2144
            "content": "Audio 1: <|audio_bos|><|AUDIO|><|audio_eos|>\nWhat does the "
            "audio say?",
2145
2146
        }
    ]
2147
    _assert_mm_data_inputs(mm_data, {"audio": 1})
2148
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[audio_uuid])
2149
2150
2151
2152
2153
2154
2155


@pytest.mark.asyncio
async def test_parse_chat_messages_single_empty_audio_with_uuid_async(
    qwen2_audio_model_config,
):
    audio_uuid = "abcd"
2156
    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
        [
            {
                "role": "user",
                "content": [
                    {
                        "type": "input_audio",
                        "input_audio": {},
                        "uuid": audio_uuid,
                    },
                    {"type": "text", "text": "What does the audio say?"},
                ],
            }
        ],
2170
        qwen2_audio_model_config,
2171
2172
2173
        content_format="string",
    )

2174
2175
2176
    assert conversation == [
        {
            "role": "user",
2177
2178
            "content": "Audio 1: <|audio_bos|><|AUDIO|><|audio_eos|>\nWhat does the "
            "audio say?",
2179
2180
        }
    ]
2181
    _assert_mm_data_inputs(mm_data, {"audio": 1})
2182
    _assert_mm_uuids(mm_uuids, 1, modality="audio", expected_uuids=[audio_uuid])
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684


def test_parse_chat_messages_image_vision_chunk(
    kimi_k2_5_model_config,
    image_url,
):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this image."},
                {
                    "type": "image_url",
                    "image_url": {"url": image_url},
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = parse_chat_messages(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    placeholder = "<|media_begin|>image<|media_content|><|media_pad|><|media_end|>"
    expected_conversation = [
        {
            "role": "user",
            "content": f"{placeholder}\nAnalyze this image.",
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None], modality="vision_chunk")


def test_parse_chat_messages_video_vision_chunk(
    kimi_k2_5_model_config,
    video_url,
):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this video."},
                {
                    "type": "video_url",
                    "video_url": {"url": video_url},
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = parse_chat_messages(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    placeholder = "<|kimi_k25_video_placeholder|>"
    expected_conversation = [
        {
            "role": "user",
            "content": f"{placeholder}\nAnalyze this video.",
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None], modality="vision_chunk")


def test_parse_chat_messages_image_vision_chunk_with_uuid(
    kimi_k2_5_model_config,
    image_url,
):
    image_uuid = "image_123"
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this image."},
                {
                    "type": "image_url",
                    "image_url": {"url": image_url},
                    "uuid": image_uuid,
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = parse_chat_messages(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    placeholder = "<|media_begin|>image<|media_content|><|media_pad|><|media_end|>"
    expected_conversation = [
        {
            "role": "user",
            "content": f"{placeholder}\nAnalyze this image.",
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid], modality="vision_chunk")


def test_parse_chat_messages_video_vision_chunk_with_uuid(
    kimi_k2_5_model_config,
    video_url,
):
    video_uuid = "video_456"
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this video."},
                {
                    "type": "video_url",
                    "video_url": {"url": video_url},
                    "uuid": video_uuid,
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = parse_chat_messages(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    placeholder = "<|kimi_k25_video_placeholder|>"
    expected_conversation = [
        {
            "role": "user",
            "content": f"{placeholder}\nAnalyze this video.",
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[video_uuid], modality="vision_chunk")


def test_parse_chat_messages_mixed_vision_chunk(
    kimi_k2_5_model_config,
    image_url,
    video_url,
):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this image and video."},
                {
                    "type": "image_url",
                    "image_url": {"url": image_url},
                },
                {
                    "type": "video_url",
                    "video_url": {"url": video_url},
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = parse_chat_messages(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    image_placeholder = (
        "<|media_begin|>image<|media_content|><|media_pad|><|media_end|>"
    )
    video_placeholder = "<|kimi_k25_video_placeholder|>"
    expected_conversation = [
        {
            "role": "user",
            "content": (
                f"{image_placeholder}\n{video_placeholder}\n"
                "Analyze this image and video."
            ),
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None], modality="vision_chunk")


def test_parse_chat_messages_mixed_vision_chunk_with_uuid(
    kimi_k2_5_model_config,
    image_url,
    video_url,
):
    image_uuid = "image_123"
    video_uuid = "video_456"
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this image and video."},
                {
                    "type": "image_url",
                    "image_url": {"url": image_url},
                    "uuid": image_uuid,
                },
                {
                    "type": "video_url",
                    "video_url": {"url": video_url},
                    "uuid": video_uuid,
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = parse_chat_messages(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    image_placeholder = (
        "<|media_begin|>image<|media_content|><|media_pad|><|media_end|>"
    )
    video_placeholder = "<|kimi_k25_video_placeholder|>"
    expected_conversation = [
        {
            "role": "user",
            "content": (
                f"{image_placeholder}\n{video_placeholder}\n"
                "Analyze this image and video."
            ),
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 2)
    _assert_mm_uuids(
        mm_uuids, 2, expected_uuids=[image_uuid, video_uuid], modality="vision_chunk"
    )


@pytest.mark.asyncio
async def test_parse_chat_messages_mixed_vision_chunk_async(
    kimi_k2_5_model_config,
    image_url,
    video_url,
):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this image and video."},
                {
                    "type": "image_url",
                    "image_url": {"url": image_url},
                },
                {
                    "type": "video_url",
                    "video_url": {"url": video_url},
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    image_placeholder = (
        "<|media_begin|>image<|media_content|><|media_pad|><|media_end|>"
    )
    video_placeholder = "<|kimi_k25_video_placeholder|>"
    expected_conversation = [
        {
            "role": "user",
            "content": (
                f"{image_placeholder}\n{video_placeholder}\n"
                "Analyze this image and video."
            ),
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 2)
    _assert_mm_uuids(mm_uuids, 2, expected_uuids=[None, None], modality="vision_chunk")


@pytest.mark.asyncio
async def test_parse_chat_messages_mixed_vision_chunk_with_uuid_async(
    kimi_k2_5_model_config,
    image_url,
    video_url,
):
    image_uuid = "image_123"
    video_uuid = "video_456"
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this image and video."},
                {
                    "type": "image_url",
                    "image_url": {"url": image_url},
                    "uuid": image_uuid,
                },
                {
                    "type": "video_url",
                    "video_url": {"url": video_url},
                    "uuid": video_uuid,
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    image_placeholder = (
        "<|media_begin|>image<|media_content|><|media_pad|><|media_end|>"
    )
    video_placeholder = "<|kimi_k25_video_placeholder|>"
    expected_conversation = [
        {
            "role": "user",
            "content": (
                f"{image_placeholder}\n{video_placeholder}\n"
                "Analyze this image and video."
            ),
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 2)
    _assert_mm_uuids(
        mm_uuids, 2, expected_uuids=[image_uuid, video_uuid], modality="vision_chunk"
    )


@pytest.mark.asyncio
async def test_parse_chat_messages_image_vision_chunk_async(
    kimi_k2_5_model_config,
    image_url,
):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this image."},
                {
                    "type": "image_url",
                    "image_url": {"url": image_url},
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    placeholder = "<|media_begin|>image<|media_content|><|media_pad|><|media_end|>"
    expected_conversation = [
        {
            "role": "user",
            "content": f"{placeholder}\nAnalyze this image.",
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None], modality="vision_chunk")


@pytest.mark.asyncio
async def test_parse_chat_messages_video_vision_chunk_async(
    kimi_k2_5_model_config,
    video_url,
):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this video."},
                {
                    "type": "video_url",
                    "video_url": {"url": video_url},
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    placeholder = "<|kimi_k25_video_placeholder|>"
    expected_conversation = [
        {
            "role": "user",
            "content": f"{placeholder}\nAnalyze this video.",
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[None], modality="vision_chunk")


@pytest.mark.asyncio
async def test_parse_chat_messages_image_vision_chunk_with_uuid_async(
    kimi_k2_5_model_config,
    image_url,
):
    image_uuid = "image_123"
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this image."},
                {
                    "type": "image_url",
                    "image_url": {"url": image_url},
                    "uuid": image_uuid,
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    placeholder = "<|media_begin|>image<|media_content|><|media_pad|><|media_end|>"
    expected_conversation = [
        {
            "role": "user",
            "content": f"{placeholder}\nAnalyze this image.",
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[image_uuid], modality="vision_chunk")


@pytest.mark.asyncio
async def test_parse_chat_messages_video_vision_chunk_with_uuid_async(
    kimi_k2_5_model_config,
    video_url,
):
    video_uuid = "video_456"
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this video."},
                {
                    "type": "video_url",
                    "video_url": {"url": video_url},
                    "uuid": video_uuid,
                },
            ],
        }
    ]

    conversation, mm_data, mm_uuids = await parse_chat_messages_async(
        messages,
        kimi_k2_5_model_config,
        content_format="string",
    )

    placeholder = "<|kimi_k25_video_placeholder|>"
    expected_conversation = [
        {
            "role": "user",
            "content": f"{placeholder}\nAnalyze this video.",
        }
    ]

    assert conversation == expected_conversation
    _assert_mm_data_is_vision_chunk_input(mm_data, 1)
    _assert_mm_uuids(mm_uuids, 1, expected_uuids=[video_uuid], modality="vision_chunk")