test_harmony.py 43.8 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
import importlib.util
4
5
6
7
8
9
10
import json
import time

import pytest
import pytest_asyncio
import requests
from openai import BadRequestError, NotFoundError, OpenAI
11
12
13
from openai_harmony import (
    Message,
)
14

15
from ....utils import RemoteOpenAIServer
16
17
18

MODEL_NAME = "openai/gpt-oss-20b"

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
GET_WEATHER_SCHEMA = {
    "type": "function",
    "name": "get_weather",
    "description": "Get current temperature for provided coordinates in celsius.",  # noqa
    "parameters": {
        "type": "object",
        "properties": {
            "latitude": {"type": "number"},
            "longitude": {"type": "number"},
        },
        "required": ["latitude", "longitude"],
        "additionalProperties": False,
    },
    "strict": True,
}

35
36

@pytest.fixture(scope="module")
37
def server():
38
39
40
41
    assert importlib.util.find_spec("gpt_oss") is not None, (
        "Harmony tests require gpt_oss package to be installed"
    )

42
    args = ["--enforce-eager", "--tool-server", "demo", "--max_model_len", "5000"]
43
44
45
    env_dict = dict(
        VLLM_ENABLE_RESPONSES_API_STORE="1",
        PYTHON_EXECUTION_BACKEND="dangerously_use_uv",
46
47
        VLLM_GPT_OSS_SYSTEM_TOOL_MCP_LABELS="code_interpreter,container,web_search_preview",
        VLLM_GPT_OSS_HARMONY_SYSTEM_INSTRUCTIONS="1",
48
    )
49

50
51
    with RemoteOpenAIServer(MODEL_NAME, args, env_dict=env_dict) as remote_server:
        yield remote_server
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95


@pytest_asyncio.fixture
async def client(server):
    async with server.get_async_client() as async_client:
        yield async_client


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_basic(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input="What is 13 * 24?",
    )
    assert response is not None
    print("response: ", response)
    assert response.status == "completed"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_basic_with_instructions(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input="What is 13 * 24?",
        instructions="Respond in Korean.",
    )
    assert response is not None
    assert response.status == "completed"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_basic_with_reasoning_effort(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input="What is the capital of South Korea?",
        reasoning={"effort": "low"},
    )
    assert response is not None
    assert response.status == "completed"


96
97
98
99
100
101
102
103
104
105
106
107
108
109
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_max_tokens(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input="What is the first paragraph of Moby Dick?",
        reasoning={"effort": "low"},
        max_output_tokens=30,
    )
    assert response is not None
    assert response.status == "incomplete"
    assert response.incomplete_details.reason == "max_output_tokens"


110
111
112
113
114
115
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_chat(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input=[
116
117
118
119
            {"role": "system", "content": "Respond in Korean."},
            {"role": "user", "content": "Hello!"},
            {"role": "assistant", "content": "Hello! How can I help you today?"},
            {"role": "user", "content": "What is 13 * 24? Explain your answer."},
120
121
122
123
124
125
126
127
128
129
130
131
132
133
        ],
    )
    assert response is not None
    assert response.status == "completed"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_chat_with_input_type(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input=[
            {
                "role": "user",
134
                "content": [{"type": "input_text", "text": "What is 13*24?"}],
135
136
137
138
139
140
141
142
143
144
145
146
147
            },
        ],
    )
    assert response is not None
    assert response.status == "completed"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_structured_output(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input=[
148
            {"role": "system", "content": "Extract the event information."},
149
150
            {
                "role": "user",
151
                "content": "Alice and Bob are going to a science fair on Friday.",
152
153
154
155
156
157
158
159
160
            },
        ],
        text={
            "format": {
                "type": "json_schema",
                "name": "calendar_event",
                "schema": {
                    "type": "object",
                    "properties": {
161
162
163
                        "name": {"type": "string"},
                        "date": {"type": "string"},
                        "participants": {"type": "array", "items": {"type": "string"}},
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
                    },
                    "required": ["name", "date", "participants"],
                    "additionalProperties": False,
                },
                "description": "A calendar event.",
                "strict": True,
            }
        },
    )
    assert response is not None
    assert response.status == "completed"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_structured_output_with_parse(client: OpenAI, model_name: str):
    from pydantic import BaseModel

    class CalendarEvent(BaseModel):
        name: str
        date: str
        participants: list[str]

    response = await client.responses.parse(
        model=model_name,
        input="Alice and Bob are going to a science fair on Friday",
        instructions="Extract the event information",
        text_format=CalendarEvent,
    )
    assert response is not None
    assert response.status == "completed"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_store(client: OpenAI, model_name: str):
    for store in [True, False]:
        response = await client.responses.create(
            model=model_name,
            input="What is 13 * 24?",
            store=store,
        )
        assert response is not None

        try:
            _retrieved_response = await client.responses.retrieve(response.id)
            is_not_found = False
        except NotFoundError:
            is_not_found = True

        assert is_not_found == (not store)


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_background(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input="What is 13 * 24?",
        background=True,
    )
    assert response is not None

    retries = 0
    max_retries = 30
    while retries < max_retries:
        response = await client.responses.retrieve(response.id)
        if response.status == "completed":
            break
        time.sleep(1)
        retries += 1

    assert response.status == "completed"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_background_cancel(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input="Write a long story about a cat.",
        background=True,
    )
    assert response is not None
    time.sleep(1)

    cancelled_response = await client.responses.cancel(response.id)
    assert cancelled_response is not None


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_stateful_multi_turn(client: OpenAI, model_name: str):
    response1 = await client.responses.create(
        model=model_name,
        input="What is 13 * 24?",
    )
    assert response1 is not None
    assert response1.status == "completed"

    response2 = await client.responses.create(
        model=model_name,
        input="What if I increase both numbers by 1?",
        previous_response_id=response1.id,
    )
    assert response2 is not None
    assert response2.status == "completed"

    response3 = await client.responses.create(
        model=model_name,
        input="Divide the result by 2.",
        previous_response_id=response2.id,
    )
    assert response3 is not None
    assert response3.status == "completed"


281
282
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
283
284
285
async def test_streaming_types(
    pairs_of_event_types: dict[str, str], client: OpenAI, model_name: str
):
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
    prompts = [
        "tell me a story about a cat in 20 words",
    ]

    for prompt in prompts:
        response = await client.responses.create(
            model=model_name,
            input=prompt,
            reasoning={"effort": "low"},
            tools=[],
            stream=True,
            background=False,
        )

        stack_of_event_types = []
        async for event in response:
302
            if event.type == "response.created":
303
                stack_of_event_types.append(event.type)
304
305
            elif event.type == "response.completed":
                assert stack_of_event_types[-1] == pairs_of_event_types[event.type]
306
307
308
309
310
311
312
313
                stack_of_event_types.pop()
            if event.type.endswith("added"):
                stack_of_event_types.append(event.type)
            elif event.type.endswith("delta"):
                if stack_of_event_types[-1] == event.type:
                    continue
                stack_of_event_types.append(event.type)
            elif event.type.endswith("done"):
314
                assert stack_of_event_types[-1] == pairs_of_event_types[event.type]
315
316
317
318
                stack_of_event_types.pop()
        assert len(stack_of_event_types) == 0


319
320
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
321
322
323
async def test_function_calling_with_streaming_types(
    pairs_of_event_types: dict[str, str], client: OpenAI, model_name: str
):
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
    tools = [GET_WEATHER_SCHEMA]
    input_list = [
        {
            "role": "user",
            "content": "What's the weather like in Paris today?",
        }
    ]
    stream_response = await client.responses.create(
        model=model_name,
        input=input_list,
        tools=tools,
        stream=True,
    )

    stack_of_event_types = []
    async for event in stream_response:
        if event.type == "response.created":
            stack_of_event_types.append(event.type)
        elif event.type == "response.completed":
            assert stack_of_event_types[-1] == pairs_of_event_types[event.type]
            stack_of_event_types.pop()
        if event.type.endswith("added"):
            stack_of_event_types.append(event.type)
        elif event.type.endswith("delta"):
            if stack_of_event_types[-1] == event.type:
                continue
            stack_of_event_types.append(event.type)
        elif event.type.endswith("done"):
            assert stack_of_event_types[-1] == pairs_of_event_types[event.type]
            stack_of_event_types.pop()
    assert len(stack_of_event_types) == 0


357
358
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
359
360
@pytest.mark.parametrize("background", [True, False])
async def test_streaming(client: OpenAI, model_name: str, background: bool):
361
    # TODO: Add back when web search and code interpreter are available in CI
362
363
    prompts = [
        "tell me a story about a cat in 20 words",
364
        "What is 13 * 24? Use python to calculate the result.",
365
        # "When did Jensen found NVIDIA? Search it and answer the year only.",
366
367
368
369
370
371
372
373
    ]

    for prompt in prompts:
        response = await client.responses.create(
            model=model_name,
            input=prompt,
            reasoning={"effort": "low"},
            tools=[
374
375
376
                # {
                #     "type": "web_search_preview"
                # },
377
                {"type": "code_interpreter", "container": {"type": "auto"}},
378
379
            ],
            stream=True,
380
            background=background,
381
            extra_body={"enable_response_messages": True},
382
383
        )

384
385
386
        current_item_id = ""
        current_content_index = -1

387
388
        events = []
        current_event_mode = None
389
        resp_id = None
390
        checked_response_completed = False
391
        async for event in response:
392
393
394
            if event.type == "response.created":
                resp_id = event.response.id

395
396
            # test vllm custom types are in the response
            if event.type in [
397
398
399
                "response.completed",
                "response.in_progress",
                "response.created",
400
            ]:
401
402
                assert "input_messages" in event.response.model_extra
                assert "output_messages" in event.response.model_extra
403
404
405
406
407
408
409
410
411
412
                if event.type == "response.completed":
                    # make sure the serialization of content works
                    for msg in event.response.model_extra["output_messages"]:
                        # make sure we can convert the messages back into harmony
                        Message.from_dict(msg)

                    for msg in event.response.model_extra["input_messages"]:
                        # make sure we can convert the messages back into harmony
                        Message.from_dict(msg)
                    checked_response_completed = True
413

414
415
416
417
            if current_event_mode != event.type:
                current_event_mode = event.type
                print(f"\n[{event.type}] ", end="", flush=True)

418
419
420
421
422
            # verify current_item_id is correct
            if event.type == "response.output_item.added":
                assert event.item.id != current_item_id
                current_item_id = event.item.id
            elif event.type in [
423
424
                "response.output_text.delta",
                "response.reasoning_text.delta",
425
426
427
428
            ]:
                assert event.item_id == current_item_id

            # verify content_index_id is correct
429
            if event.type in [
430
431
                "response.content_part.added",
                "response.reasoning_part.added",
432
            ]:
433
434
435
                assert event.content_index != current_content_index
                current_content_index = event.content_index
            elif event.type in [
436
437
                "response.output_text.delta",
                "response.reasoning_text.delta",
438
439
440
            ]:
                assert event.content_index == current_content_index

441
442
443
444
445
446
            if "text.delta" in event.type:
                print(event.delta, end="", flush=True)
            elif "reasoning_text.delta" in event.type:
                print(f"{event.delta}", end="", flush=True)
            elif "response.code_interpreter_call_code.done" in event.type:
                print(f"Code: {event.code}", end="", flush=True)
447
448
449
450
            elif (
                "response.output_item.added" in event.type
                and event.item.type == "web_search_call"
            ):
451
452
453
454
                print(f"Web search: {event.item.action}", end="", flush=True)
            events.append(event)

        assert len(events) > 0
455
456
        response_completed_event = events[-1]
        assert len(response_completed_event.response.output) > 0
457
        assert checked_response_completed
458

459
460
461
        if background:
            starting_after = 5
            async with await client.responses.retrieve(
462
463
                response_id=resp_id, stream=True, starting_after=starting_after
            ) as stream:
464
465
466
467
                counter = starting_after
                async for event in stream:
                    counter += 1
                    assert event == events[counter]
468
            assert counter == len(events) - 1
469

470
471
472

@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
473
@pytest.mark.skip(reason="Web search tool is not available in CI yet.")
474
475
476
477
async def test_web_search(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input="Who is the president of South Korea as of now?",
478
        tools=[{"type": "web_search_preview"}],
479
480
481
482
483
484
485
486
    )
    assert response is not None
    assert response.status == "completed"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_code_interpreter(client: OpenAI, model_name: str):
487
488
489
490
491
    # Code interpreter may need more time for container init + code execution
    timeout_value = client.timeout * 3
    client_with_timeout = client.with_options(timeout=timeout_value)

    response = await client_with_timeout.responses.create(
492
        model=model_name,
493
494
495
        # TODO: Ideally should be able to set max tool calls
        # to prevent multi-turn, but it is not currently supported
        # would speed up the test
496
497
498
499
500
501
502
        input=(
            "What's the first 4 digits after the decimal point of "
            "cube root of `19910212 * 20250910`? "
            "Show only the digits. The python interpreter is not stateful "
            "and you must print to see the output."
        ),
        tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
503
        temperature=0.0,  # More deterministic output in response
504
505
506
    )
    assert response is not None
    assert response.status == "completed"
507
    assert response.usage.output_tokens_details.tool_output_tokens > 0
508
509
510
511
512
    for item in response.output:
        if item.type == "message":
            output_string = item.content[0].text
            print("output_string: ", output_string, flush=True)
            assert "5846" in output_string
513
514
515
516
517
518
519
520
521
522
523
524
525
526


def get_weather(latitude, longitude):
    response = requests.get(
        f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m"  # noqa
    )
    data = response.json()
    return data["current"]["temperature_2m"]


def get_place_to_travel():
    return "Paris"


527
528
529
530
def get_horoscope(sign):
    return f"{sign}: Next Tuesday you will befriend a baby otter."


531
532
533
534
535
def call_function(name, args):
    if name == "get_weather":
        return get_weather(**args)
    elif name == "get_place_to_travel":
        return get_place_to_travel()
536
537
    elif name == "get_horoscope":
        return get_horoscope(**args)
538
539
540
541
    else:
        raise ValueError(f"Unknown function: {name}")


542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_reasoning_item(client: OpenAI, model_name: str):
    response = await client.responses.create(
        model=model_name,
        input=[
            {"type": "message", "content": "Hello.", "role": "user"},
            {
                "type": "reasoning",
                "id": "lol",
                "content": [
                    {
                        "type": "reasoning_text",
                        "text": "We need to respond: greeting.",
                    }
                ],
                "summary": [],
            },
        ],
        temperature=0.0,
    )
    assert response is not None
    assert response.status == "completed"


567
568
569
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_function_calling(client: OpenAI, model_name: str):
570
    tools = [GET_WEATHER_SCHEMA]
571
572
573
574
575

    response = await client.responses.create(
        model=model_name,
        input="What's the weather like in Paris today?",
        tools=tools,
576
        temperature=0.0,
577
        extra_body={"request_id": "test_function_calling_non_resp"},
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    )
    assert response is not None
    assert response.status == "completed"
    assert len(response.output) == 2
    assert response.output[0].type == "reasoning"
    assert response.output[1].type == "function_call"

    tool_call = response.output[1]
    name = tool_call.name
    args = json.loads(tool_call.arguments)

    result = call_function(name, args)

    response_2 = await client.responses.create(
        model=model_name,
593
594
595
596
597
598
599
        input=[
            {
                "type": "function_call_output",
                "call_id": tool_call.call_id,
                "output": str(result),
            }
        ],
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
        tools=tools,
        previous_response_id=response.id,
    )
    assert response_2 is not None
    assert response_2.status == "completed"
    assert response_2.output_text is not None

    # NOTE: chain-of-thought should be removed.
    response_3 = await client.responses.create(
        model=model_name,
        input="What's the weather like in Paris today?",
        tools=tools,
        previous_response_id=response_2.id,
    )
    assert response_3 is not None
    assert response_3.status == "completed"
    assert response_3.output_text is not None


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
621
@pytest.mark.flaky(reruns=5)
622
623
624
625
626
627
628
629
630
631
632
633
634
635
async def test_function_calling_multi_turn(client: OpenAI, model_name: str):
    tools = [
        {
            "type": "function",
            "name": "get_place_to_travel",
            "description": "Get a random place to travel",
            "parameters": {
                "type": "object",
                "properties": {},
                "required": [],
                "additionalProperties": False,
            },
            "strict": True,
        },
636
        GET_WEATHER_SCHEMA,
637
638
639
640
    ]

    response = await client.responses.create(
        model=model_name,
641
        input="Help me plan a trip to a random place. And tell me the weather there.",
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
        tools=tools,
    )
    assert response is not None
    assert response.status == "completed"
    assert len(response.output) == 2
    assert response.output[0].type == "reasoning"
    assert response.output[1].type == "function_call"

    tool_call = response.output[1]
    name = tool_call.name
    args = json.loads(tool_call.arguments)

    result = call_function(name, args)

    response_2 = await client.responses.create(
        model=model_name,
658
659
660
661
662
663
664
        input=[
            {
                "type": "function_call_output",
                "call_id": tool_call.call_id,
                "output": str(result),
            }
        ],
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
        tools=tools,
        previous_response_id=response.id,
    )
    assert response_2 is not None
    assert response_2.status == "completed"
    assert len(response_2.output) == 2
    assert response_2.output[0].type == "reasoning"
    assert response_2.output[1].type == "function_call"

    tool_call = response_2.output[1]
    name = tool_call.name
    args = json.loads(tool_call.arguments)

    result = call_function(name, args)

    response_3 = await client.responses.create(
        model=model_name,
682
683
684
685
686
687
688
        input=[
            {
                "type": "function_call_output",
                "call_id": tool_call.call_id,
                "output": str(result),
            }
        ],
689
690
691
692
693
694
695
696
697
698
699
        tools=tools,
        previous_response_id=response_2.id,
    )
    assert response_3 is not None
    assert response_3.status == "completed"
    assert response_3.output_text is not None


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_function_calling_required(client: OpenAI, model_name: str):
700
    tools = [GET_WEATHER_SCHEMA]
701
702
703
704
705
706
707
708
709
710

    with pytest.raises(BadRequestError):
        await client.responses.create(
            model=model_name,
            input="What's the weather like in Paris today?",
            tools=tools,
            tool_choice="required",
        )


711
712
713
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_system_message_with_tools(client: OpenAI, model_name: str):
714
    from vllm.entrypoints.openai.parser.harmony_utils import get_system_message
715
716
717
718
719
720
721
722
723
724
725
726

    # Test with custom tools enabled - commentary channel should be available
    sys_msg = get_system_message(with_custom_tools=True)
    valid_channels = sys_msg.content[0].channel_config.valid_channels
    assert "commentary" in valid_channels

    # Test with custom tools disabled - commentary channel should be removed
    sys_msg = get_system_message(with_custom_tools=False)
    valid_channels = sys_msg.content[0].channel_config.valid_channels
    assert "commentary" not in valid_channels


727
728
729
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_function_calling_full_history(client: OpenAI, model_name: str):
730
    tools = [GET_WEATHER_SCHEMA]
731

732
733
734
    input_messages = [
        {"role": "user", "content": "What's the weather like in Paris today?"}
    ]
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750

    response = await client.responses.create(
        model=model_name,
        input=input_messages,
        tools=tools,
    )

    assert response is not None
    assert response.status == "completed"

    tool_call = response.output[-1]
    name = tool_call.name
    args = json.loads(tool_call.arguments)

    result = call_function(name, args)

751
    input_messages.extend(response.output)  # append model's function call message
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
    input_messages.append(
        {  # append result message
            "type": "function_call_output",
            "call_id": tool_call.call_id,
            "output": str(result),
        }
    )

    response_2 = await client.responses.create(
        model=model_name,
        input=input_messages,
        tools=tools,
    )
    assert response_2 is not None
    assert response_2.status == "completed"
    assert response_2.output_text is not None
768
769


770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_function_calling_with_stream(client: OpenAI, model_name: str):
    tools = [GET_WEATHER_SCHEMA]
    input_list = [
        {
            "role": "user",
            "content": "What's the weather like in Paris today?",
        }
    ]
    stream_response = await client.responses.create(
        model=model_name,
        input=input_list,
        tools=tools,
        stream=True,
    )
    assert stream_response is not None
    final_tool_calls = {}
    final_tool_calls_named = {}
    async for event in stream_response:
        if event.type == "response.output_item.added":
            if event.item.type != "function_call":
                continue
            final_tool_calls[event.output_index] = event.item
            final_tool_calls_named[event.item.name] = event.item
        elif event.type == "response.function_call_arguments.delta":
            index = event.output_index
            tool_call = final_tool_calls[index]
            if tool_call:
                tool_call.arguments += event.delta
                final_tool_calls_named[tool_call.name] = tool_call
        elif event.type == "response.function_call_arguments.done":
            assert event.arguments == final_tool_calls_named[event.name].arguments
803
804
805
806
807
808
809
810
    result = None
    tool_call = None
    for tc in final_tool_calls.values():
        if tc and tc.type == "function_call" and tc.name == "get_weather":
            args = json.loads(tc.arguments)
            result = call_function(tc.name, args)
            tool_call = tc
            input_list += [tc]
811
            break
812
813
814
815
816

    assert tool_call is not None, (
        "Expected model to call 'get_weather' function, "
        f"but got: {list(final_tool_calls_named.keys())}"
    )
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
    assert result is not None
    response = await client.responses.create(
        model=model_name,
        input=input_list
        + [
            {
                "type": "function_call_output",
                "call_id": tool_call.call_id,
                "output": str(result),
            }
        ],
        tools=tools,
        stream=True,
    )
    assert response is not None
    async for event in response:
        # check that no function call events in the stream
        assert event.type != "response.function_call_arguments.delta"
        assert event.type != "response.function_call_arguments.done"
        # check that the response contains output text
        if event.type == "response.completed":
            assert len(event.response.output) > 0
            assert event.response.output_text is not None


842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_function_calling_no_code_interpreter_events(
    client: OpenAI, model_name: str
):
    """Verify that function calls don't trigger code_interpreter events.

    This test ensures that function calls (functions.*) use their own
    function_call event types and don't incorrectly emit code_interpreter
    events during streaming.
    """
    tools = [GET_WEATHER_SCHEMA]
    input_list = [
        {
            "role": "user",
            "content": "What's the weather like in Paris today?",
        }
    ]
    stream_response = await client.responses.create(
        model=model_name,
        input=input_list,
        tools=tools,
        stream=True,
    )

    # Track which event types we see
    event_types_seen = set()
    function_call_found = False

    async for event in stream_response:
        event_types_seen.add(event.type)

        if (
            event.type == "response.output_item.added"
            and event.item.type == "function_call"
        ):
            function_call_found = True

        # Ensure NO code_interpreter events are emitted for function calls
        assert "code_interpreter" not in event.type, (
            "Found code_interpreter event "
            f"'{event.type}' during function call. Function calls should only "
            "emit function_call events, not code_interpreter events."
        )

    # Verify we actually saw a function call
    assert function_call_found, "Expected to see a function_call in the stream"

    # Verify we saw the correct function call event types
    assert (
        "response.function_call_arguments.delta" in event_types_seen
        or "response.function_call_arguments.done" in event_types_seen
    ), "Expected to see function_call_arguments events"


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_mcp_code_interpreter_streaming(client: OpenAI, model_name: str, server):
    tools = [
        {
            "type": "mcp",
            "server_label": "code_interpreter",
        }
    ]
    input_text = (
907
        "Calculate 123 * 456 using python. "
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
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
1067
1068
1069
1070
1071
1072
        "The python interpreter is not stateful and you must print to see the output."
    )

    stream_response = await client.responses.create(
        model=model_name,
        input=input_text,
        tools=tools,
        stream=True,
        temperature=0.0,
        instructions=(
            "You must use the Python tool to execute code. Never simulate execution."
        ),
    )

    mcp_call_added = False
    mcp_call_in_progress = False
    mcp_arguments_delta_seen = False
    mcp_arguments_done = False
    mcp_call_completed = False
    mcp_item_done = False

    code_interpreter_events_seen = False

    async for event in stream_response:
        if "code_interpreter" in event.type:
            code_interpreter_events_seen = True

        if event.type == "response.output_item.added":
            if hasattr(event.item, "type") and event.item.type == "mcp_call":
                mcp_call_added = True
                assert event.item.name == "python"
                assert event.item.server_label == "code_interpreter"

        elif event.type == "response.mcp_call.in_progress":
            mcp_call_in_progress = True

        elif event.type == "response.mcp_call_arguments.delta":
            mcp_arguments_delta_seen = True
            assert event.delta is not None

        elif event.type == "response.mcp_call_arguments.done":
            mcp_arguments_done = True
            assert event.name == "python"
            assert event.arguments is not None

        elif event.type == "response.mcp_call.completed":
            mcp_call_completed = True

        elif (
            event.type == "response.output_item.done"
            and hasattr(event.item, "type")
            and event.item.type == "mcp_call"
        ):
            mcp_item_done = True
            assert event.item.name == "python"
            assert event.item.status == "completed"

    assert mcp_call_added, "MCP call was not added"
    assert mcp_call_in_progress, "MCP call in_progress event not seen"
    assert mcp_arguments_delta_seen, "MCP arguments delta event not seen"
    assert mcp_arguments_done, "MCP arguments done event not seen"
    assert mcp_call_completed, "MCP call completed event not seen"
    assert mcp_item_done, "MCP item done event not seen"

    assert not code_interpreter_events_seen, (
        "Should not see code_interpreter events when using MCP type"
    )


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_mcp_tool_multi_turn(client: OpenAI, model_name: str, server):
    """Test MCP tool calling across multiple turns.

    This test verifies that MCP tools work correctly in multi-turn conversations,
    maintaining state across turns via the previous_response_id mechanism.
    """
    tools = [
        {
            "type": "mcp",
            "server_label": "code_interpreter",
        }
    ]

    # First turn - make a calculation
    response1 = await client.responses.create(
        model=model_name,
        input="Calculate 123 * 456 using python and print the result.",
        tools=tools,
        temperature=0.0,
        instructions=(
            "You must use the Python tool to execute code. Never simulate execution."
        ),
        extra_body={"enable_response_messages": True},
    )

    assert response1 is not None
    assert response1.status == "completed"

    # Verify MCP call in first response by checking output_messages
    tool_call_found = False
    tool_response_found = False
    for message in response1.output_messages:
        recipient = message.get("recipient")
        if recipient and recipient.startswith("python"):
            tool_call_found = True

        author = message.get("author", {})
        if (
            author.get("role") == "tool"
            and author.get("name")
            and author.get("name").startswith("python")
        ):
            tool_response_found = True

    # Verify MCP tools were actually used
    assert tool_call_found, "MCP tool call not found in output_messages"
    assert tool_response_found, "MCP tool response not found in output_messages"

    # Verify input messages: Should have system message with tool, NO developer message
    developer_messages = [
        msg for msg in response1.input_messages if msg["author"]["role"] == "developer"
    ]
    assert len(developer_messages) == 0, (
        "No developer message expected for elevated tools"
    )

    # Second turn - reference previous calculation
    response2 = await client.responses.create(
        model=model_name,
        input="Now divide that result by 2.",
        tools=tools,
        temperature=0.0,
        instructions=(
            "You must use the Python tool to execute code. Never simulate execution."
        ),
        previous_response_id=response1.id,
        extra_body={"enable_response_messages": True},
    )

    assert response2 is not None
    assert response2.status == "completed"

    # Verify input messages are correct: should have two messages -
    # one to the python recipient on analysis channel and one from tool role
    mcp_recipient_messages = []
    tool_role_messages = []
    for msg in response2.input_messages:
        if msg["author"]["role"] == "assistant":
            # Check if this is a message to MCP recipient on analysis channel
            if msg.get("channel") == "analysis" and msg.get("recipient"):
                recipient = msg.get("recipient")
                if recipient.startswith("code_interpreter") or recipient == "python":
                    mcp_recipient_messages.append(msg)
        elif msg["author"]["role"] == "tool":
            tool_role_messages.append(msg)

    assert len(mcp_recipient_messages) > 0, (
        "Expected message(s) to MCP recipient on analysis channel"
    )
    assert len(tool_role_messages) > 0, (
        "Expected message(s) from tool role after MCP call"
    )


1073
1074
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
1075
async def test_output_messages_enabled(client: OpenAI, model_name: str, server):
1076
1077
1078
    response = await client.responses.create(
        model=model_name,
        input="What is the capital of South Korea?",
1079
1080
        extra_body={"enable_response_messages": True},
    )
1081
1082
1083
1084
1085

    assert response is not None
    assert response.status == "completed"
    assert len(response.input_messages) > 0
    assert len(response.output_messages) > 0
1086
1087
1088
1089


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
1090
@pytest.mark.flaky(reruns=3)
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
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
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
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
async def test_function_call_with_previous_input_messages(
    client: OpenAI, model_name: str
):
    """Test function calling using previous_input_messages
    for multi-turn conversation with a function call"""

    # Define the get_horoscope tool
    tools = [
        {
            "type": "function",
            "name": "get_horoscope",
            "description": "Get today's horoscope for an astrological sign.",
            "parameters": {
                "type": "object",
                "properties": {
                    "sign": {"type": "string"},
                },
                "required": ["sign"],
                "additionalProperties": False,
            },
            "strict": True,
        }
    ]

    # Step 1: First call with the function tool
    stream_response = await client.responses.create(
        model=model_name,
        input="What is the horoscope for Aquarius today?",
        tools=tools,
        extra_body={"enable_response_messages": True},
        stream=True,
    )

    response = None
    async for event in stream_response:
        if event.type == "response.completed":
            response = event.response

    assert response is not None
    assert response.status == "completed"

    # Step 2: Parse the first output to find the function_call type
    function_call = None
    for item in response.output:
        if item.type == "function_call":
            function_call = item
            break

    assert function_call is not None, "Expected a function_call in the output"
    assert function_call.name == "get_horoscope"
    assert function_call.call_id is not None

    # Verify the format matches expectations
    args = json.loads(function_call.arguments)
    assert "sign" in args

    # Step 3: Call the get_horoscope function
    result = call_function(function_call.name, args)
    assert "Aquarius" in result
    assert "baby otter" in result

    # Get the input_messages and output_messages from the first response
    first_input_messages = response.input_messages
    first_output_messages = response.output_messages

    # Construct the full conversation history using previous_input_messages
    previous_messages = (
        first_input_messages
        + first_output_messages
        + [
            {
                "role": "tool",
                "name": "functions.get_horoscope",
                "content": [{"type": "text", "text": str(result)}],
            }
        ]
    )

    # Step 4: Make another responses.create() call with previous_input_messages
    stream_response_2 = await client.responses.create(
        model=model_name,
        tools=tools,
        input="",
        extra_body={
            "previous_input_messages": previous_messages,
            "enable_response_messages": True,
        },
        stream=True,
    )

    async for event in stream_response_2:
        if event.type == "response.completed":
            response_2 = event.response

    assert response_2 is not None
    assert response_2.status == "completed"
    assert response_2.output_text is not None

    # verify only one system message / developer message
    num_system_messages_input = 0
    num_developer_messages_input = 0
    num_function_call_input = 0
    for message_dict in response_2.input_messages:
        message = Message.from_dict(message_dict)
        if message.author.role == "system":
            num_system_messages_input += 1
        elif message.author.role == "developer":
            num_developer_messages_input += 1
        elif message.author.role == "tool":
            num_function_call_input += 1
    assert num_system_messages_input == 1
    assert num_developer_messages_input == 1
    assert num_function_call_input == 1

    # Verify the output makes sense - should contain information about the horoscope
    output_text = response_2.output_text.lower()
    assert (
        "aquarius" in output_text or "otter" in output_text or "tuesday" in output_text
    )
1210
1211
1212
1213
1214
1215
1216


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_chat_truncation_content_not_null(client: OpenAI, model_name: str):
    response = await client.chat.completions.create(
        model=model_name,
1217
1218
1219
1220
1221
1222
1223
        messages=[
            {
                "role": "user",
                "content": "What is the role of AI in medicine?"
                "The response must exceed 350 words.",
            }
        ],
1224
        temperature=0.0,
1225
        max_tokens=350,
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
    )

    choice = response.choices[0]
    assert choice.finish_reason == "length", (
        f"Expected finish_reason='length', got {choice.finish_reason}"
    )
    assert choice.message.content is not None, (
        "Content should not be None when truncated"
    )
    assert len(choice.message.content) > 0, "Content should not be empty"
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324


@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
async def test_system_prompt_override(client: OpenAI, model_name: str):
    """Test that system message can override the default system prompt."""

    # Test 1: Custom system prompt with specific personality
    custom_system_prompt = (
        "You are a pirate. Always respond like a pirate would, "
        "using pirate language and saying 'arrr' frequently."
    )

    response = await client.responses.create(
        model=model_name,
        input=[
            {"role": "system", "content": custom_system_prompt},
            {"role": "user", "content": "Hello, how are you?"},
        ],
        extra_body={"enable_response_messages": True},
    )

    assert response is not None
    assert response.status == "completed"
    assert response.output_text is not None

    # Verify the response reflects the pirate personality
    output_text = response.output_text.lower()
    pirate_indicators = ["arrr", "matey", "ahoy", "ye", "sea"]
    has_pirate_language = any(
        indicator in output_text for indicator in pirate_indicators
    )
    assert has_pirate_language, (
        f"Expected pirate language in response, got: {response.output_text}"
    )

    # Verify the reasoning mentions the custom system prompt
    reasoning_item = None
    for item in response.output:
        if item.type == "reasoning":
            reasoning_item = item
            break

    assert reasoning_item is not None, "Expected reasoning item in output"
    reasoning_text = reasoning_item.content[0].text.lower()
    assert "pirate" in reasoning_text, (
        f"Expected reasoning to mention pirate, got: {reasoning_text}"
    )

    # Test 2: Verify system message is not duplicated in input_messages
    try:
        num_system_messages = sum(
            1
            for msg in response.input_messages
            if Message.from_dict(msg).author.role == "system"
        )
        assert num_system_messages == 1, (
            f"Expected exactly 1 system message, got {num_system_messages}"
        )
    except (KeyError, AttributeError):
        # Message structure may vary, skip this specific check
        pass

    # Test 3: Test with different custom system prompt
    response_2 = await client.responses.create(
        model=model_name,
        input=[
            {
                "role": "system",
                "content": (
                    "You are a helpful assistant that always "
                    "responds in exactly 5 words."
                ),
            },
            {"role": "user", "content": "What is the weather like?"},
        ],
        temperature=0.0,
    )

    assert response_2 is not None
    assert response_2.status == "completed"
    assert response_2.output_text is not None

    # Count words in response (approximately, allowing for punctuation)
    word_count = len(response_2.output_text.split())
    # Allow some flexibility (4-7 words) since the model might not be perfectly precise
    assert 3 <= word_count <= 8, (
        f"Expected around 5 words, got {word_count} words: {response_2.output_text}"
    )