-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathtest_harmony.py
More file actions
1266 lines (1041 loc) · 42.8 KB
/
Copy pathtest_harmony.py
File metadata and controls
1266 lines (1041 loc) · 42.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
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
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
907
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
"""Port of the original Rust test-suite to Python.
The tests mirror the scenarios from ``src/tests.rs`` and exercise the public
Python API. They ensure that the bindings give byte-for-byte identical output
to the canonical Rust implementation.
"""
# ruff: noqa: E402 # postpone imports until path manipulation is done
from __future__ import annotations
import sys
from pathlib import Path
from typing import List
# Ensure that the project root is on *sys.path* so that ``import harmony``
# picks up the local Python package during test execution (pytest changes the
# working directory which would otherwise hide the module).
ROOT_DIR = Path(__file__).resolve().parent.parent
if str(ROOT_DIR) not in sys.path:
sys.path.insert(0, str(ROOT_DIR))
import pytest # noqa: E402
from openai_harmony import ( # noqa: E402
Author,
Conversation,
DeveloperContent,
HarmonyEncodingName,
HarmonyError,
Message,
ReasoningEffort,
RenderConversationConfig,
Role,
StreamableParser,
SystemContent,
ToolDescription,
load_harmony_encoding,
)
from pydantic import ValidationError
# ---------------------------------------------------------------------------
# Helper
# ---------------------------------------------------------------------------
def _assert_tokens_eq(encoding, expected: List[int], actual: List[int]): # type: ignore[arg-type]
"""Mimic the pretty-assertions output from the Rust test-suite."""
if expected != actual:
exp_decoded = encoding.decode_utf8(expected)
act_decoded = encoding.decode_utf8(actual)
raise AssertionError(
"tokens are not equal.\n\n"
"Tokens (< expected / actual >):\n"
f"{expected}\n{actual}\n\n"
"Decoded (< expected / actual >):\n"
f"{exp_decoded!r}\n{act_decoded!r}"
)
def read_expected_tokens(file_path: Path) -> List[int]:
with open(file_path, "r", encoding="utf-8") as f:
return [int(x) for x in f.read().split()]
# ---------------------------------------------------------------------------
# Tests (1-1 port from the Rust side)
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"encoding_name",
[
HarmonyEncodingName.HARMONY_GPT_OSS,
],
)
def test_simple_convo(encoding_name):
encoding = load_harmony_encoding(encoding_name)
expected_text = (
(ROOT_DIR / "test-data" / "test_simple_convo.txt")
.read_text(encoding="utf-8")
.rstrip()
)
expected_tokens = encoding.encode(expected_text, allowed_special="all")
convo = Conversation.from_messages(
[
Message.from_role_and_content(
Role.SYSTEM,
SystemContent.new().with_model_identity(
"You are ChatGPT, a large language model trained by OpenAI."
),
),
Message.from_role_and_content(Role.USER, "What is 2 + 2?"),
]
)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
_assert_tokens_eq(encoding, expected_tokens, tokens)
@pytest.mark.parametrize(
"encoding_name",
[
HarmonyEncodingName.HARMONY_GPT_OSS,
],
)
def test_simple_convo_with_effort(encoding_name):
encoding = load_harmony_encoding(encoding_name)
test_cases = [
(
ReasoningEffort.LOW,
ROOT_DIR / "test-data" / "test_simple_convo_low_effort.txt",
True,
),
(
ReasoningEffort.MEDIUM,
ROOT_DIR / "test-data" / "test_simple_convo_medium_effort.txt",
True,
),
(
ReasoningEffort.HIGH,
ROOT_DIR / "test-data" / "test_simple_convo_high_effort.txt",
True,
),
(
ReasoningEffort.LOW,
ROOT_DIR / "test-data" / "test_simple_convo_low_effort_no_instruction.txt",
False,
),
(
ReasoningEffort.MEDIUM,
ROOT_DIR
/ "test-data"
/ "test_simple_convo_medium_effort_no_instruction.txt",
False,
),
(
ReasoningEffort.HIGH,
ROOT_DIR / "test-data" / "test_simple_convo_high_effort_no_instruction.txt",
False,
),
]
for effort, tokens_path, use_instruction in test_cases:
expected_text = tokens_path.read_text(encoding="utf-8").rstrip()
expected_tokens = encoding.encode(expected_text, allowed_special="all")
sys = (
SystemContent.new()
.with_model_identity(
"You are ChatGPT, a large language model trained by OpenAI."
)
.with_reasoning_effort(effort)
)
messages = [Message.from_role_and_content(Role.SYSTEM, sys)]
if use_instruction:
dev = DeveloperContent.new().with_instructions(
"Answer the user's questions like a robot."
)
messages.append(Message.from_role_and_content(Role.DEVELOPER, dev))
messages.append(
Message.from_role_and_content(
Role.USER,
"What is the capital of the largest country in the world?",
)
)
convo = Conversation.from_messages(messages)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
_assert_tokens_eq(encoding, expected_tokens, tokens)
@pytest.mark.parametrize(
"encoding_name",
[
HarmonyEncodingName.HARMONY_GPT_OSS,
],
)
def test_simple_reasoning_response(encoding_name):
encoding = load_harmony_encoding(encoding_name)
expected_tokens = read_expected_tokens(
ROOT_DIR / "test-data" / "test_simple_reasoning_response.txt"
)
messages = encoding.parse_messages_from_completion_tokens(
expected_tokens, role=Role.ASSISTANT
)
expected = [
Message.from_role_and_content(
Role.ASSISTANT,
'User asks: "What is 2 + 2?" Simple arithmetic. Provide answer.',
).with_channel("analysis"),
Message.from_role_and_content(Role.ASSISTANT, "2 + 2 = 4.").with_channel(
"final"
),
]
assert messages == expected
@pytest.mark.parametrize(
"encoding_name",
[
HarmonyEncodingName.HARMONY_GPT_OSS,
],
)
def test_simple_tool_call(encoding_name):
encoding = load_harmony_encoding(encoding_name)
response = read_expected_tokens(
ROOT_DIR / "test-data" / "test_simple_tool_call.txt"
)
parsed = encoding.parse_messages_from_completion_tokens(
response,
role=Role.ASSISTANT,
)
expected = [
Message.from_role_and_content(
Role.ASSISTANT,
'User asks: "What is the weather in Tokyo?" We need to use lookup_weather tool.',
).with_channel("analysis"),
Message.from_role_and_content(Role.ASSISTANT, '{"location": "Tokyo"}')
.with_channel("analysis")
.with_recipient("lookup_weather")
.with_content_type("code"),
]
assert parsed == expected
@pytest.mark.parametrize(
"encoding_name",
[
HarmonyEncodingName.HARMONY_GPT_OSS,
],
)
def test_tool_call_with_constrain_tokenized_correctly(encoding_name):
"""
Despite passing <|constrain|> as a string in "content_type" it has to be kept as a special token.
"""
encoding = load_harmony_encoding(encoding_name)
text = (
"<|start|>assistant to=functions.get_weather<|channel|>commentary"
' <|constrain|>json<|message|>{"location": "Tokyo"}<|call|>'
)
tokens = encoding.encode(text, allowed_special="all")
parsed = encoding.parse_messages_from_completion_tokens(tokens, role=None)
expected = [
Message.from_role_and_content(Role.ASSISTANT, '{"location": "Tokyo"}')
.with_channel("commentary")
.with_recipient("functions.get_weather")
.with_content_type("<|constrain|>json"),
]
assert parsed == expected
rendered = encoding.render_conversation(Conversation.from_messages(expected))
assert text == encoding.decode_utf8(tokens)
assert rendered == tokens
@pytest.mark.parametrize(
"encoding_name",
[
HarmonyEncodingName.HARMONY_GPT_OSS,
],
)
def test_tool_call_with_constrain_marker_adjacent(encoding_name):
"""
There are moments where the model might not output a space before constrain resulting in the
content type being parsed as part of the recipient. This test ensures that we handle this case
correctly and instead handle it as a separate content type.
"""
encoding = load_harmony_encoding(encoding_name)
text = (
"<|start|>assistant to=functions.get_weather<|channel|>commentary"
'<|constrain|>json<|message|>{"location": "Tokyo"}<|call|>'
)
tokens = encoding.encode(text, allowed_special="all")
parsed = encoding.parse_messages_from_completion_tokens(tokens, role=None)
expected = [
Message.from_role_and_content(Role.ASSISTANT, '{"location": "Tokyo"}')
.with_channel("commentary")
.with_recipient("functions.get_weather")
.with_content_type("<|constrain|>json"),
]
assert parsed == expected
@pytest.mark.parametrize(
"encoding_name",
[
HarmonyEncodingName.HARMONY_GPT_OSS,
],
)
def test_tool_call_with_channel_before_recipient_and_constrain_adjacent(
encoding_name,
):
encoding = load_harmony_encoding(encoding_name)
text = (
"<|start|>assistant<|channel|>commentary to=functions.get_weather"
'<|constrain|>json<|message|>{"latitude":48.8566,"longitude":2.3522}<|call|>'
)
tokens = encoding.encode(text, allowed_special="all")
parsed = encoding.parse_messages_from_completion_tokens(tokens, role=None)
expected = [
Message.from_role_and_content(
Role.ASSISTANT, '{"latitude":48.8566,"longitude":2.3522}'
)
.with_channel("commentary")
.with_recipient("functions.get_weather")
.with_content_type("<|constrain|>json"),
]
assert parsed == expected
@pytest.mark.parametrize(
"encoding_name",
[
HarmonyEncodingName.HARMONY_GPT_OSS,
],
)
def test_reasoning_system_message(encoding_name):
encoding = load_harmony_encoding(encoding_name)
expected_text = (
(ROOT_DIR / "test-data" / "test_reasoning_system_message.txt")
.read_text(encoding="utf-8")
.rstrip()
)
expected = encoding.encode(expected_text, allowed_special="all")
sys = (
SystemContent.new()
.with_model_identity(
"You are ChatGPT, a large language model trained by OpenAI."
)
.with_reasoning_effort(ReasoningEffort.MEDIUM)
.with_required_channels(["analysis", "final"])
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(Role.SYSTEM, sys),
Message.from_role_and_content(Role.USER, "What is 2 + 2?"),
]
)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
_assert_tokens_eq(encoding, expected, tokens)
@pytest.mark.parametrize(
"encoding_name",
[
HarmonyEncodingName.HARMONY_GPT_OSS,
],
)
def test_reasoning_system_message_no_instruction(encoding_name):
encoding = load_harmony_encoding(encoding_name)
expected_text = (
(ROOT_DIR / "test-data" / "test_reasoning_system_message_no_instruction.txt")
.read_text(encoding="utf-8")
.rstrip()
)
expected = encoding.encode(expected_text, allowed_special="all")
sys = (
SystemContent.new()
.with_model_identity(
"You are ChatGPT, a large language model trained by OpenAI."
)
.with_reasoning_effort(ReasoningEffort.HIGH)
.with_required_channels(["analysis", "final"])
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(Role.SYSTEM, sys),
Message.from_role_and_content(
Role.USER,
"What is the best place to eat candy in the world?",
),
]
)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
_assert_tokens_eq(encoding, expected, tokens)
@pytest.mark.parametrize(
"encoding_name",
[
HarmonyEncodingName.HARMONY_GPT_OSS,
],
)
def test_reasoning_system_message_with_dates(encoding_name):
encoding = load_harmony_encoding(encoding_name)
expected_text = (
(ROOT_DIR / "test-data" / "test_reasoning_system_message_with_dates.txt")
.read_text(encoding="utf-8")
.rstrip()
)
expected = encoding.encode(expected_text, allowed_special="all")
sys = (
SystemContent.new()
.with_model_identity(
"You are ChatGPT, a large language model trained by OpenAI."
)
.with_reasoning_effort(ReasoningEffort.MEDIUM)
.with_conversation_start_date("2021-01-01")
.with_knowledge_cutoff("2021-01")
.with_required_channels(["analysis", "final"])
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(Role.SYSTEM, sys),
Message.from_role_and_content(Role.USER, "What is 42 * pi?"),
]
)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
_assert_tokens_eq(encoding, expected, tokens)
def test_render_functions_with_parameters():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
expected_output = (
(ROOT_DIR / "test-data" / "test_render_functions_with_parameters.txt")
.read_text(encoding="utf-8")
.rstrip()
)
sys = (
SystemContent.new()
.with_reasoning_effort(ReasoningEffort.HIGH)
.with_conversation_start_date("2025-06-28")
)
dev = (
DeveloperContent.new()
.with_instructions("Always respond in riddles")
.with_function_tools(
[
ToolDescription.new(
"get_location",
"Gets the location of the user.",
),
ToolDescription.new(
"get_current_weather",
"Gets the current weather in the provided location.",
parameters={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"format": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"default": "celsius",
},
},
"required": ["location"],
},
),
ToolDescription.new(
"get_multiple_weathers",
"Gets the current weather in the provided list of locations.",
parameters={
"type": "object",
"properties": {
"locations": {
"type": "array",
"items": {
"type": "string",
},
"description": 'List of city and state, e.g. ["San Francisco, CA", "New York, NY"]',
},
"format": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"default": "celsius",
},
},
"required": ["locations"],
},
),
ToolDescription.new(
"kitchensink",
"A function with various complex schemas.",
parameters={
"description": "params object",
"type": "object",
"properties": {
"string": {
"type": "string",
"title": "STRING",
"description": "A string",
"examples": ["hello", "world"],
},
"string_nullable": {
"type": "string",
"nullable": True,
"description": "A nullable string",
"default": "the default",
},
"string_enum": {"type": "string", "enum": ["a", "b", "c"]},
"oneof_string_or_number": {
"oneOf": [
{
"type": "string",
"default": "default_string_in_oneof",
},
{
"type": "number",
"description": "numbers can happen too",
},
],
"description": "a oneof",
"default": 20,
},
},
},
),
]
)
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(Role.SYSTEM, sys),
Message.from_role_and_content(Role.DEVELOPER, dev),
Message.from_role_and_content(Role.USER, "What is the weather like in SF?"),
]
)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
assert encoding.decode_utf8(tokens) == expected_output
def test_no_tools():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
expected_output = (
(ROOT_DIR / "test-data" / "test_no_tools.txt")
.read_text(encoding="utf-8")
.rstrip()
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(
Role.SYSTEM,
SystemContent.new().with_conversation_start_date("2025-06-28"),
),
]
)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
assert encoding.decode_utf8(tokens) == expected_output
def test_browser_tool_only():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
expected_output = (
(ROOT_DIR / "test-data" / "test_browser_tool_only.txt")
.read_text(encoding="utf-8")
.rstrip()
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(
Role.SYSTEM,
SystemContent.new()
.with_conversation_start_date("2025-06-28")
.with_browser_tool(),
),
]
)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
assert encoding.decode_utf8(tokens) == expected_output
def test_browser_and_function_tool():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
expected_output = (
(ROOT_DIR / "test-data" / "test_browser_and_function_tool.txt")
.read_text(encoding="utf-8")
.rstrip()
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(
Role.SYSTEM,
SystemContent.new()
.with_conversation_start_date("2025-06-28")
.with_browser_tool(),
),
Message.from_role_and_content(
Role.DEVELOPER,
DeveloperContent.new().with_function_tools(
[
ToolDescription.new(
"lookup_weather",
"Use this tool to lookup the weather in a given location. Call it with the parameter 'location', can be any textual description of a location.",
parameters={
"type": "object",
"properties": {
"location": {"type": "string"},
},
"required": ["location"],
},
)
]
),
),
]
)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
assert encoding.decode_utf8(tokens) == expected_output
def test_browser_and_python_tool():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
expected_output = (
(ROOT_DIR / "test-data" / "test_browser_and_python_tool.txt")
.read_text(encoding="utf-8")
.rstrip()
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(
Role.SYSTEM,
SystemContent.new()
.with_conversation_start_date("2025-06-28")
.with_browser_tool()
.with_python_tool(),
),
]
)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
assert encoding.decode_utf8(tokens) == expected_output
def test_dropping_cot_by_default():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
expected_output = (
(ROOT_DIR / "test-data" / "test_dropping_cot_by_default.txt")
.read_text(encoding="utf-8")
.rstrip()
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(Role.USER, "What is 2 + 2?"),
Message.from_role_and_content(
Role.ASSISTANT,
"User asks: “What is 2 + 2?” Simple arithmetic. Provide answer.",
).with_channel("analysis"),
Message.from_role_and_content(
Role.ASSISTANT, "2 + 2 equals 4."
).with_channel("final"),
Message.from_role_and_content(Role.USER, "What about 9 / 2?"),
]
)
tokens = encoding.render_conversation_for_completion(
convo, Role.ASSISTANT, RenderConversationConfig(auto_drop_analysis=True)
)
assert encoding.decode_utf8(tokens) == expected_output
def test_does_not_drop_if_ongoing_analysis():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
expected_output = (
(ROOT_DIR / "test-data" / "test_does_not_drop_if_ongoing_analysis.txt")
.read_text(encoding="utf-8")
.rstrip()
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(Role.USER, "What is the weather in SF?"),
Message.from_role_and_content(
Role.ASSISTANT,
"User asks: “What is the weather in SF?” We need to use lookup_weather tool.",
).with_channel("analysis"),
Message.from_role_and_content(
Role.ASSISTANT, '{"location": "San Francisco"}'
)
.with_channel("commentary")
.with_recipient("functions.lookup_weather")
.with_content_type("<|constrain|>json"),
Message.from_author_and_content(
Author.new(Role.TOOL, "functions.lookup_weather"),
'{"temperature": 20, "description": "sunny"}',
),
]
)
tokens = encoding.render_conversation_for_completion(
convo, Role.ASSISTANT, RenderConversationConfig(auto_drop_analysis=True)
)
assert encoding.decode_utf8(tokens) == expected_output
# ensure that <|constrain|>json part is tokenized correctly as special tokens
assert encoding.encode(expected_output, allowed_special="all") == tokens
def test_preserve_cot():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
expected_output = (
(ROOT_DIR / "test-data" / "test_preserve_cot.txt")
.read_text(encoding="utf-8")
.rstrip()
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(Role.USER, "What is 2 + 2?"),
Message.from_role_and_content(
Role.ASSISTANT,
'User asks a simple question: "What is 2 + 2?" The answer: 4.',
).with_channel("analysis"),
Message.from_role_and_content(
Role.ASSISTANT, "2 + 2 equals 4."
).with_channel("final"),
Message.from_role_and_content(Role.USER, "What about 9 / 2?"),
]
)
tokens = encoding.render_conversation_for_completion(
convo, Role.ASSISTANT, RenderConversationConfig(auto_drop_analysis=False)
)
assert encoding.decode_utf8(tokens) == expected_output
def test_reserved_token_decoding():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
assert encoding.decode_utf8([200014]) == "<|reserved_200014|>"
assert encoding.decode_utf8([201088]) == "<|reserved_201088|>"
def test_keep_analysis_between_final_messages():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
expected_output = (
(ROOT_DIR / "test-data" / "test_keep_analysis_between_finals.txt")
.read_text(encoding="utf-8")
.rstrip()
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(Role.USER, "What is 2 + 2?"),
Message.from_role_and_content(Role.ASSISTANT, "thinking 2+2").with_channel(
"analysis"
),
Message.from_role_and_content(Role.ASSISTANT, "4").with_channel("final"),
Message.from_role_and_content(Role.USER, "What is 3 + 5?"),
Message.from_role_and_content(Role.ASSISTANT, "thinking 3+5").with_channel(
"analysis"
),
Message.from_role_and_content(Role.ASSISTANT, "8").with_channel("final"),
]
)
tokens = encoding.render_conversation(convo)
assert encoding.decode_utf8(tokens) == expected_output
def test_render_and_render_conversation_roundtrip():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
msg = Message.from_role_and_content(Role.USER, "Hello")
convo = Conversation.from_messages([msg])
tokens_msg = encoding.render(msg)
tokens_convo = encoding.render_conversation(convo)
assert tokens_msg == tokens_convo
tokens_completion = encoding.render_conversation_for_completion(
convo, Role.ASSISTANT
)
assert tokens_completion[: len(tokens_convo)] == tokens_convo
def test_render_conversation_for_training_final_channel():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
convo = Conversation.from_messages(
[
Message.from_role_and_content(Role.USER, "hi"),
Message.from_role_and_content(Role.ASSISTANT, "hello").with_channel(
"final"
),
]
)
tokens_training = encoding.render_conversation_for_training(convo)
tokens_regular = encoding.render_conversation(convo)
token_return = encoding.encode("<|return|>", allowed_special={"<|return|>"})[0]
token_end = encoding.encode("<|end|>", allowed_special={"<|end|>"})[0]
assert tokens_regular[:-1] == tokens_training[:-1]
assert tokens_regular[-1] == token_end
assert tokens_training[-1] == token_return
def test_render_conversation_for_training_non_final():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
convo = Conversation.from_messages([Message.from_role_and_content(Role.USER, "hi")])
tokens_training = encoding.render_conversation_for_training(convo)
tokens_regular = encoding.render_conversation(convo)
assert tokens_training == tokens_regular
def test_decode_utf8_invalid_token():
"""Invalid tokens should raise an exception (type doesn't matter)."""
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
with pytest.raises(HarmonyError, match="Invalid token for decoding: 99999999"):
encoding.decode_utf8([99999999])
with pytest.raises(
ValidationError,
match="Input should be a valid dictionary or instance of Message",
):
encoding.render_conversation_for_completion(
Conversation.from_messages([SystemContent.new()]),
Role.ASSISTANT,
)
def test_encode_decode_roundtrip():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
assert encoding.decode_utf8(encoding.encode("hello world")) == "hello world"
assert encoding.decode(encoding.encode("hello world")) == "hello world"
def test_encode_allowed_special():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
assert encoding.encode("hello world") == [24912, 2375]
assert encoding.encode("<|start|>", allowed_special={"<|start|>"}) == [200006]
assert encoding.encode("<|start|>", allowed_special="all") == [200006]
with pytest.raises(
HarmonyError, match="Encountered text corresponding to disallowed special token"
):
encoding.encode("<|start|>")
assert encoding.encode("<|start|>", disallowed_special=()) == [
27,
91,
5236,
91,
29,
]
def test_is_special_token():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
assert encoding.is_special_token(200006) # <|start|>
assert not encoding.is_special_token(24912) # hello
def test_invalid_utf8_decoding():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
tokens = [132990, 9552]
with pytest.raises(HarmonyError, match="Invalid utf-8"):
# This will raise an error because the tokens are invalid utf-8
encoding.decode_utf8(tokens)
# This will not raise an error because it will replace the invalid utf-8 characters to not raise an error
# to match the behavior of tiktoken
assert "Chicken" in encoding.decode(tokens)
def test_tool_response_parsing():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
text_tokens = (
(ROOT_DIR / "test-data" / "test_tool_response_parsing.txt")
.read_text(encoding="utf-8")
.rstrip()
)
expected_message = (
Message.from_author_and_content(
Author.new(Role.TOOL, "browser.search"),
'{"result": "https://openai.com/"}',
)
.with_channel("commentary")
.with_recipient("assistant")
)
output_tokens = encoding.render(expected_message)
output_tokens = output_tokens[:-1] # remove the <|end|> token
messages = encoding.parse_messages_from_completion_tokens(output_tokens, None)
assert len(messages) == 1
assert encoding.decode_utf8(output_tokens) == text_tokens
def test_streamable_parser():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
text_tokens = (
(ROOT_DIR / "test-data" / "test_streamable_parser.txt")
.read_text(encoding="utf-8")
.rstrip()
)
tokens = encoding.encode(text_tokens, allowed_special="all")
parser = StreamableParser(encoding, Role.ASSISTANT)
for token in tokens:
parser.process(token)
assert len(parser.messages) == 3
def test_streamable_parser_tool_call_with_constrain_adjacent():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
text = (
"<|start|>assistant<|channel|>commentary to=functions.get_weather"
'<|constrain|>json<|message|>{"latitude":48.8566,"longitude":2.3522}<|call|>'
)
tokens = encoding.encode(text, allowed_special="all")
parser = StreamableParser(encoding, None)
for token in tokens:
parser.process(token)
expected = [
Message.from_role_and_content(
Role.ASSISTANT, '{"latitude":48.8566,"longitude":2.3522}'
)
.with_channel("commentary")
.with_recipient("functions.get_weather")
.with_content_type("<|constrain|>json"),
]
assert parser.messages == expected
def test_streamable_parser_constrained_output_without_recipient():
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
text = (
"<|start|>assistant<|channel|>final "
'<|constrain|>json<|message|>{"result":true}<|return|>'
)
tokens = encoding.encode(text, allowed_special="all")
expected = (
Message.from_role_and_content(Role.ASSISTANT, '{"result":true}')
.with_channel("final")
.with_content_type("<|constrain|>json")
)
parser = StreamableParser(encoding, None)
for token in tokens: