forked from waybarrios/vllm-mlx
-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathtest_harmony_parsers.py
More file actions
1325 lines (1117 loc) · 47.9 KB
/
test_harmony_parsers.py
File metadata and controls
1325 lines (1117 loc) · 47.9 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
# SPDX-License-Identifier: Apache-2.0
"""
Tests for Harmony format parsers (GPT-OSS models).
Tests cover:
- HarmonyToolParser: tool call extraction from commentary channel
- HarmonyReasoningParser: reasoning extraction from analysis channel
- convert_tools_to_typescript: OpenAI JSON Schema to TypeScript conversion
Usage:
pytest tests/test_harmony_parsers.py -v
"""
import json
import pytest
from vllm_mlx.api.harmony_tools import convert_tools_to_typescript
from vllm_mlx.reasoning import get_parser
from vllm_mlx.reasoning.harmony_parser import HarmonyReasoningParser
from vllm_mlx.tool_parsers import ToolParserManager
from vllm_mlx.tool_parsers.harmony_tool_parser import HarmonyToolParser
# ============================================================================
# Tool Parser Tests
# ============================================================================
class TestHarmonyToolParser:
"""Tests for HarmonyToolParser."""
@pytest.fixture()
def parser(self):
return HarmonyToolParser()
def test_registration(self):
"""Parser is registered under harmony and gpt-oss names."""
assert ToolParserManager.get_tool_parser("harmony") is HarmonyToolParser
assert ToolParserManager.get_tool_parser("gpt-oss") is HarmonyToolParser
def test_single_tool_call(self, parser):
"""Parse a single tool call from commentary channel."""
text = (
"<|start|>\n"
"<|channel|>commentary to=functions.get_weather\n"
"<|constrain|>json\n"
'<|message|>{"location": "San Francisco", "unit": "celsius"}\n'
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
assert len(result.tool_calls) == 1
assert result.tool_calls[0]["name"] == "get_weather"
args = json.loads(result.tool_calls[0]["arguments"])
assert args["location"] == "San Francisco"
assert args["unit"] == "celsius"
def test_tool_call_with_analysis_and_final(self, parser):
"""Parse tool call when analysis and final channels are present."""
text = (
"<|start|>\n"
"<|channel|>analysis\n"
"<|message|>The user wants weather. I should call get_weather.\n"
"<|end|>\n"
"<|channel|>commentary to=functions.get_weather\n"
"<|constrain|>json\n"
'<|message|>{"location": "SF"}\n'
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
assert len(result.tool_calls) == 1
assert result.tool_calls[0]["name"] == "get_weather"
def test_final_response_only(self, parser):
"""Parse response with no tool calls (final channel only)."""
text = (
"<|start|>\n"
"<|channel|>final\n"
"<|message|>The weather in San Francisco is 72F and sunny!\n"
"<|return|>"
)
result = parser.extract_tool_calls(text)
assert not result.tools_called
assert result.tool_calls == []
assert result.content == "The weather in San Francisco is 72F and sunny!"
def test_multiple_tool_calls(self, parser):
"""Parse multiple tool calls from separate commentary blocks."""
text = (
"<|start|>\n"
"<|channel|>commentary to=functions.get_weather\n"
"<|constrain|>json\n"
'<|message|>{"location": "SF"}\n'
"<|call|>\n"
"<|channel|>commentary to=functions.get_time\n"
"<|constrain|>json\n"
'<|message|>{"timezone": "PST"}\n'
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
assert len(result.tool_calls) == 2
assert result.tool_calls[0]["name"] == "get_weather"
assert result.tool_calls[1]["name"] == "get_time"
def test_tool_call_without_constrain(self, parser):
"""Parse tool call without <|constrain|>json tag."""
text = (
"<|channel|>commentary to=functions.simple_func\n"
'<|message|>{"arg": "value"}\n'
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
assert len(result.tool_calls) == 1
assert result.tool_calls[0]["name"] == "simple_func"
def test_malformed_json_arguments(self, parser):
"""Handle malformed JSON gracefully by keeping raw string."""
text = (
"<|channel|>commentary to=functions.broken_func\n"
"<|constrain|>json\n"
"<|message|>{invalid json here}\n"
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
assert len(result.tool_calls) == 1
assert result.tool_calls[0]["name"] == "broken_func"
assert result.tool_calls[0]["arguments"] == "{invalid json here}"
def test_tool_call_with_final_content(self, parser):
"""Tool calls coexist with final channel content."""
text = (
"<|channel|>commentary to=functions.search\n"
"<|constrain|>json\n"
'<|message|>{"query": "python"}\n'
"<|call|>\n"
"<|channel|>final\n"
"<|message|>Here are the results.\n"
"<|return|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
assert len(result.tool_calls) == 1
assert result.content == "Here are the results."
def test_empty_input(self, parser):
"""Handle empty input."""
result = parser.extract_tool_calls("")
assert not result.tools_called
assert result.tool_calls == []
def test_plain_text_input(self, parser):
"""Handle plain text with no Harmony tokens."""
result = parser.extract_tool_calls("Just a regular response.")
assert not result.tools_called
assert result.content == "Just a regular response."
def test_unique_tool_ids(self, parser):
"""Each tool call gets a unique ID."""
text = (
"<|channel|>commentary to=functions.func_a\n"
"<|constrain|>json\n"
"<|message|>{}\n"
"<|call|>\n"
"<|channel|>commentary to=functions.func_b\n"
"<|constrain|>json\n"
"<|message|>{}\n"
"<|call|>"
)
result = parser.extract_tool_calls(text)
ids = [tc["id"] for tc in result.tool_calls]
assert len(set(ids)) == 2
assert all(id_.startswith("call_") for id_ in ids)
def test_nested_json_arguments(self, parser):
"""Parse tool call with nested JSON arguments."""
args = {"filter": {"type": "range", "min": 0, "max": 100}, "sort": "asc"}
text = (
"<|channel|>commentary to=functions.query\n"
"<|constrain|>json\n"
f"<|message|>{json.dumps(args)}\n"
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
parsed_args = json.loads(result.tool_calls[0]["arguments"])
assert parsed_args["filter"]["type"] == "range"
def test_streaming_no_tool_markers(self, parser):
"""Streaming: plain text passes through as content."""
result = parser.extract_tool_calls_streaming("", "Hello", "Hello")
assert result == {"content": "Hello"}
def test_streaming_tool_call_complete(self, parser):
"""Streaming: emit tool calls when <|call|> appears."""
current = (
"<|channel|>commentary to=functions.func\n"
"<|constrain|>json\n"
'<|message|>{"a": 1}\n'
"<|call|>"
)
result = parser.extract_tool_calls_streaming("", current, "<|call|>")
assert result is not None
assert "tool_calls" in result
assert result["tool_calls"][0]["function"]["name"] == "func"
def test_streaming_building_tool_call(self, parser):
"""Streaming: suppress output while building tool call."""
current = (
"<|channel|>commentary to=functions.func\n"
"<|constrain|>json\n"
'<|message|>{"a":'
)
result = parser.extract_tool_calls_streaming("", current, '{"a":')
assert result is None
# ============================================================================
# Reasoning Parser Tests
# ============================================================================
class TestHarmonyReasoningParser:
"""Tests for HarmonyReasoningParser."""
@pytest.fixture()
def parser(self):
return HarmonyReasoningParser()
def test_registration(self):
"""Parser is registered under the harmony name."""
parser_cls = get_parser("harmony")
assert parser_cls is HarmonyReasoningParser
def test_extract_analysis_and_final(self, parser):
"""Extract reasoning from analysis and content from final."""
output = (
"<|channel|>analysis\n"
"<|message|>Let me think step by step.\n"
"<|end|>\n"
"<|channel|>final\n"
"<|message|>The answer is 42.\n"
"<|return|>"
)
reasoning, content = parser.extract_reasoning(output)
assert reasoning == "Let me think step by step."
assert content == "The answer is 42."
def test_multiple_analysis_blocks(self, parser):
"""Concatenate multiple analysis blocks."""
output = (
"<|channel|>analysis\n"
"<|message|>First thought.\n"
"<|end|>\n"
"<|channel|>analysis\n"
"<|message|>Second thought.\n"
"<|end|>\n"
"<|channel|>final\n"
"<|message|>Result.\n"
"<|return|>"
)
reasoning, content = parser.extract_reasoning(output)
assert "First thought." in reasoning
assert "Second thought." in reasoning
assert content == "Result."
def test_no_analysis_channel(self, parser):
"""Output with no analysis returns None reasoning."""
output = "<|channel|>final\n<|message|>Direct answer.\n<|return|>"
reasoning, content = parser.extract_reasoning(output)
assert reasoning is None
assert content == "Direct answer."
def test_analysis_only_no_final(self, parser):
"""Output with only analysis returns None content."""
output = "<|channel|>analysis\n<|message|>Just thinking...\n<|end|>"
reasoning, content = parser.extract_reasoning(output)
assert reasoning == "Just thinking..."
assert content is None
def test_empty_input(self, parser):
"""Handle empty input."""
reasoning, content = parser.extract_reasoning("")
assert reasoning is None
assert content is None
def test_analysis_with_commentary_and_final(self, parser):
"""Ignore commentary channel, extract analysis and final."""
output = (
"<|channel|>analysis\n"
"<|message|>Need to call a tool.\n"
"<|end|>\n"
"<|channel|>commentary to=functions.search\n"
"<|constrain|>json\n"
'<|message|>{"q": "test"}\n'
"<|call|>\n"
"<|channel|>final\n"
"<|message|>Found results.\n"
"<|return|>"
)
reasoning, content = parser.extract_reasoning(output)
assert reasoning == "Need to call a tool."
assert content == "Found results."
def test_streaming_analysis_to_final(self, parser):
"""Streaming: emit reasoning for analysis, content for final."""
parser.reset_state()
# Channel switch to analysis
r1 = parser.extract_reasoning_streaming(
"", "<|channel|>analysis\n", "<|channel|>analysis\n"
)
assert r1 is None # channel switch, no content yet
# Message start
r2 = parser.extract_reasoning_streaming(
"<|channel|>analysis\n",
"<|channel|>analysis\n<|message|>",
"<|message|>",
)
assert r2 is None # message start token
# Reasoning content
r3 = parser.extract_reasoning_streaming(
"<|channel|>analysis\n<|message|>",
"<|channel|>analysis\n<|message|>Thinking",
"Thinking",
)
assert r3 is not None
assert r3.reasoning == "Thinking"
assert r3.content is None
# End of analysis
r4 = parser.extract_reasoning_streaming(
"<|channel|>analysis\n<|message|>Thinking",
"<|channel|>analysis\n<|message|>Thinking<|end|>",
"<|end|>",
)
assert r4 is None # end token
# Switch to final
r5 = parser.extract_reasoning_streaming(
"<|channel|>analysis\n<|message|>Thinking<|end|>",
"<|channel|>analysis\n<|message|>Thinking<|end|>\n<|channel|>final\n",
"\n<|channel|>final\n",
)
assert r5 is None # channel switch
# Final message content
prev = "<|channel|>analysis\n<|message|>Thinking<|end|>\n<|channel|>final\n<|message|>"
parser.extract_reasoning_streaming(
"<|channel|>analysis\n<|message|>Thinking<|end|>\n<|channel|>final\n",
prev,
"<|message|>",
)
r6 = parser.extract_reasoning_streaming(
prev,
prev + "Answer",
"Answer",
)
assert r6 is not None
assert r6.content == "Answer"
assert r6.reasoning is None
def test_streaming_reset(self, parser):
"""Reset clears internal state."""
parser._current_channel = "analysis"
parser._in_message = True
parser.reset_state()
assert parser._current_channel is None
assert parser._in_message is False
def test_streaming_commentary_passed_through(self, parser):
"""Streaming: commentary channel passes through as content for tool parser."""
parser.reset_state()
r = parser.extract_reasoning_streaming(
"",
"<|channel|>commentary to=functions.f\n",
"<|channel|>commentary to=functions.f\n",
)
assert r is not None
assert r.content == "<|channel|>commentary to=functions.f\n"
r = parser.extract_reasoning_streaming(
"<|channel|>commentary to=functions.f\n",
"<|channel|>commentary to=functions.f\n<|message|>",
"<|message|>",
)
assert r is not None
assert r.content == "<|message|>"
r = parser.extract_reasoning_streaming(
"<|channel|>commentary to=functions.f\n<|message|>",
'<|channel|>commentary to=functions.f\n<|message|>{"a":1}',
'{"a":1}',
)
assert r is not None
assert r.content == '{"a":1}'
# ============================================================================
# TypeScript Tool Converter Tests
# ============================================================================
class TestHarmonyToolDefinitionConverter:
"""Tests for convert_tools_to_typescript."""
def test_simple_tool(self):
"""Convert a simple tool with required parameters."""
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"},
},
"required": ["location"],
},
},
}
]
result = convert_tools_to_typescript(tools)
assert "namespace functions" in result
assert "get_weather" in result
assert "location: string," in result
assert "// Get weather for a location" in result
def test_optional_parameters(self):
"""Optional parameters get ? suffix."""
tools = [
{
"type": "function",
"function": {
"name": "func",
"parameters": {
"type": "object",
"properties": {
"required_param": {"type": "string"},
"optional_param": {"type": "number"},
},
"required": ["required_param"],
},
},
}
]
result = convert_tools_to_typescript(tools)
assert "required_param: string," in result
assert "optional_param?: number," in result
def test_enum_type(self):
"""Enums become TypeScript union types."""
tools = [
{
"type": "function",
"function": {
"name": "set_unit",
"parameters": {
"type": "object",
"properties": {
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
},
},
},
},
}
]
result = convert_tools_to_typescript(tools)
assert '"celsius" | "fahrenheit"' in result
def test_multiple_tools(self):
"""Multiple tools in one namespace."""
tools = [
{
"type": "function",
"function": {
"name": "func_a",
"description": "First function",
"parameters": {"type": "object", "properties": {}},
},
},
{
"type": "function",
"function": {
"name": "func_b",
"description": "Second function",
"parameters": {"type": "object", "properties": {}},
},
},
]
result = convert_tools_to_typescript(tools)
assert "func_a" in result
assert "func_b" in result
assert "// First function" in result
assert "// Second function" in result
def test_no_tools(self):
"""None input returns None."""
assert convert_tools_to_typescript(None) is None
assert convert_tools_to_typescript([]) is None
def test_no_parameters(self):
"""Tool with no parameters uses empty signature."""
tools = [
{
"type": "function",
"function": {
"name": "ping",
"parameters": {"type": "object", "properties": {}},
},
}
]
result = convert_tools_to_typescript(tools)
assert "type ping = () => any;" in result
def test_array_type(self):
"""Array types convert to Array<type>."""
tools = [
{
"type": "function",
"function": {
"name": "process",
"parameters": {
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {"type": "string"},
},
},
},
},
}
]
result = convert_tools_to_typescript(tools)
assert "Array<string>" in result
def test_boolean_and_integer_types(self):
"""Boolean and integer map correctly."""
tools = [
{
"type": "function",
"function": {
"name": "config",
"parameters": {
"type": "object",
"properties": {
"enabled": {"type": "boolean"},
"count": {"type": "integer"},
},
},
},
}
]
result = convert_tools_to_typescript(tools)
assert "enabled?: boolean," in result
assert "count?: number," in result
def test_no_description(self):
"""Tool without description has no comment line."""
tools = [
{
"type": "function",
"function": {
"name": "no_desc",
"parameters": {"type": "object", "properties": {}},
},
}
]
result = convert_tools_to_typescript(tools)
assert "//" not in result
assert "no_desc" in result
def test_skips_non_function_types(self):
"""Non-function tools are skipped."""
tools = [
{"type": "retrieval"},
{
"type": "function",
"function": {
"name": "real_func",
"parameters": {"type": "object", "properties": {}},
},
},
]
result = convert_tools_to_typescript(tools)
assert "real_func" in result
assert "retrieval" not in result
# ============================================================================
# Edge Case Tests
# ============================================================================
class TestHarmonyEdgeCases:
"""Edge case tests for Harmony parsers."""
def test_tool_parser_incomplete_call(self):
"""Incomplete tool call (missing <|call|>) is not parsed."""
parser = HarmonyToolParser()
text = '<|channel|>commentary to=functions.func\n<|message|>{"arg": "value"}'
result = parser.extract_tool_calls(text)
assert not result.tools_called
def test_tool_parser_unicode_content(self):
"""Handle unicode in tool arguments."""
parser = HarmonyToolParser()
text = (
"<|channel|>commentary to=functions.translate\n"
"<|constrain|>json\n"
'<|message|>{"text": "日本語テスト"}\n'
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
args = json.loads(result.tool_calls[0]["arguments"])
assert args["text"] == "日本語テスト"
def test_reasoning_parser_unicode_content(self):
"""Handle unicode in reasoning and content."""
parser = HarmonyReasoningParser()
output = (
"<|channel|>analysis\n"
"<|message|>让我想想...\n"
"<|end|>\n"
"<|channel|>final\n"
"<|message|>答案是42。\n"
"<|return|>"
)
reasoning, content = parser.extract_reasoning(output)
assert reasoning == "让我想想..."
assert content == "答案是42。"
def test_mixed_channels_full_flow(self):
"""Full flow: analysis -> commentary -> analysis -> final."""
text = (
"<|start|>\n"
"<|channel|>analysis\n"
"<|message|>Think 1.\n"
"<|end|>\n"
"<|channel|>commentary to=functions.search\n"
"<|constrain|>json\n"
'<|message|>{"q": "test"}\n'
"<|call|>\n"
"<|channel|>analysis\n"
"<|message|>Think 2.\n"
"<|end|>\n"
"<|channel|>final\n"
"<|message|>Done.\n"
"<|return|>"
)
# Tool parser finds tool calls
tool_parser = HarmonyToolParser()
tool_result = tool_parser.extract_tool_calls(text)
assert tool_result.tools_called
assert len(tool_result.tool_calls) == 1
assert tool_result.tool_calls[0]["name"] == "search"
assert tool_result.content == "Done."
# Reasoning parser finds both analysis blocks
reasoning_parser = HarmonyReasoningParser()
reasoning, content = reasoning_parser.extract_reasoning(text)
assert "Think 1." in reasoning
assert "Think 2." in reasoning
assert content == "Done."
def test_tool_parser_empty_arguments(self):
"""Tool call with empty JSON arguments."""
parser = HarmonyToolParser()
text = (
"<|channel|>commentary to=functions.ping\n"
"<|constrain|>json\n"
"<|message|>{}\n"
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
assert json.loads(result.tool_calls[0]["arguments"]) == {}
def test_tool_parser_whitespace_handling(self):
"""Handle extra whitespace in Harmony format."""
parser = HarmonyToolParser()
text = (
"<|channel|>commentary to=functions.func\n"
"<|constrain|>json\n"
'<|message|> {"key": "value"} \n'
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
args = json.loads(result.tool_calls[0]["arguments"])
assert args["key"] == "value"
# ============================================================================
# Comprehensive Tool Parser Tests (extract_tool_calls)
# ============================================================================
class TestHarmonyExtractToolCalls:
"""Extended tests for HarmonyToolParser.extract_tool_calls."""
@pytest.fixture()
def parser(self):
return HarmonyToolParser()
def test_single_tool_with_analysis_and_commentary(self, parser):
"""Single tool call with analysis + commentary channels present."""
text = (
"<|start|>\n"
"<|channel|>analysis\n"
"<|message|>User wants weather info for London.\n"
"<|end|>\n"
"<|channel|>commentary to=functions.get_weather\n"
"<|constrain|>json\n"
'<|message|>{"city": "London", "units": "metric"}\n'
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
assert len(result.tool_calls) == 1
assert result.tool_calls[0]["name"] == "get_weather"
args = json.loads(result.tool_calls[0]["arguments"])
assert args["city"] == "London"
assert args["units"] == "metric"
# No final channel, so content is None
assert result.content is None
def test_tool_call_with_constrain_token(self, parser):
"""Tool call that includes <|constrain|>json is parsed correctly."""
text = (
"<|channel|>commentary to=functions.calculate\n"
"<|constrain|>json\n"
'<|message|>{"expression": "2+2"}\n'
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
assert result.tool_calls[0]["name"] == "calculate"
def test_multiple_tool_calls_with_final(self, parser):
"""Multiple tool calls with a final channel response."""
text = (
"<|channel|>commentary to=functions.search\n"
"<|constrain|>json\n"
'<|message|>{"query": "python tutorials"}\n'
"<|call|>\n"
"<|channel|>commentary to=functions.search\n"
"<|constrain|>json\n"
'<|message|>{"query": "rust tutorials"}\n'
"<|call|>\n"
"<|channel|>commentary to=functions.bookmark\n"
"<|constrain|>json\n"
'<|message|>{"url": "https://example.com"}\n'
"<|call|>\n"
"<|channel|>final\n"
"<|message|>I've searched for both and bookmarked the result.\n"
"<|return|>"
)
result = parser.extract_tool_calls(text)
assert result.tools_called
assert len(result.tool_calls) == 3
assert result.tool_calls[0]["name"] == "search"
assert result.tool_calls[1]["name"] == "search"
assert result.tool_calls[2]["name"] == "bookmark"
assert result.content == "I've searched for both and bookmarked the result."
def test_no_tool_call_final_channel_only(self, parser):
"""No tool call, final channel only -- returns content, no tools."""
text = "<|channel|>final\n<|message|>Sure, I can help with that.\n<|return|>"
result = parser.extract_tool_calls(text)
assert not result.tools_called
assert result.tool_calls == []
assert result.content == "Sure, I can help with that."
def test_no_tool_call_no_final_channel(self, parser):
"""No tool call, no final channel -- falls back to stripped text."""
text = "Hello, how can I help you today?"
result = parser.extract_tool_calls(text)
assert not result.tools_called
assert result.tool_calls == []
assert result.content == "Hello, how can I help you today?"
def test_no_tool_call_with_control_tokens_stripped(self, parser):
"""Text with stray control tokens but no proper tool call structure."""
text = "<|start|>\nHere is some text with tokens.\n<|end|>"
result = parser.extract_tool_calls(text)
assert not result.tools_called
# Control tokens should be stripped
assert "Here is some text with tokens." in result.content
def test_empty_string(self, parser):
"""Empty input returns no tools, empty content."""
result = parser.extract_tool_calls("")
assert not result.tools_called
assert result.tool_calls == []
assert result.content == ""
def test_only_whitespace(self, parser):
"""Whitespace-only input."""
result = parser.extract_tool_calls(" \n\n ")
assert not result.tools_called
assert result.tool_calls == []
def test_malformed_missing_call_tag(self, parser):
"""Commentary block without <|call|> is not a complete tool call."""
text = (
"<|channel|>commentary to=functions.func\n"
"<|constrain|>json\n"
'<|message|>{"key": "value"}\n'
# Missing <|call|>
)
result = parser.extract_tool_calls(text)
assert not result.tools_called
def test_malformed_missing_message_tag(self, parser):
"""Commentary block without <|message|> tag."""
text = (
"<|channel|>commentary to=functions.func\n"
"<|constrain|>json\n"
'{"key": "value"}\n'
"<|call|>"
)
result = parser.extract_tool_calls(text)
# The regex requires <|message|>, so this should not match
assert not result.tools_called
def test_tool_id_format(self, parser):
"""Tool IDs have the expected call_ prefix format."""
text = (
"<|channel|>commentary to=functions.test_func\n"
"<|constrain|>json\n"
'<|message|>{"a": 1}\n'
"<|call|>"
)
result = parser.extract_tool_calls(text)
assert result.tool_calls[0]["id"].startswith("call_")
assert len(result.tool_calls[0]["id"]) > len("call_")
# ============================================================================
# Comprehensive Streaming Tests
# ============================================================================
class TestHarmonyStreaming:
"""Extended tests for HarmonyToolParser.extract_tool_calls_streaming."""
@pytest.fixture()
def parser(self):
return HarmonyToolParser()
def test_token_by_token_analysis_commentary_call(self, parser):
"""Simulate token-by-token: analysis -> commentary -> call -> emits tool_calls."""
# Build up the text incrementally
chunks = [
"<|channel|>analysis\n",
"<|message|>Let me think.\n",
"<|end|>\n",
"<|channel|>commentary to=functions.get_weather\n",
"<|constrain|>json\n",
'<|message|>{"location": "NYC"}\n',
"<|call|>",
]
previous = ""
results = []
for chunk in chunks:
current = previous + chunk
result = parser.extract_tool_calls_streaming(previous, current, chunk)
results.append(result)
previous = current
# All chunks except the last should return None (suppressed during build)
for r in results[:-1]:
assert r is None, f"Expected None during build-up, got {r}"
# Last chunk (<|call|>) should emit tool_calls
final = results[-1]
assert final is not None
assert "tool_calls" in final
assert final["tool_calls"][0]["function"]["name"] == "get_weather"
args = json.loads(final["tool_calls"][0]["function"]["arguments"])
assert args["location"] == "NYC"
def test_final_channel_streaming_emits_content(self, parser):
"""Final channel tokens are emitted as content after <|message|>."""
# Build final channel token by token
base = ""
chunks = [
"<|channel|>final\n",
"<|message|>",
"The ",
"weather ",
"is ",
"sunny.",
]
previous = ""
content_parts = []
for chunk in chunks:
current = previous + chunk
result = parser.extract_tool_calls_streaming(previous, current, chunk)
if result and result.get("content"):
content_parts.append(result["content"])
previous = current
joined = "".join(content_parts)
assert joined == "The weather is sunny."
def test_final_channel_empty_content_before_message(self, parser):
"""In final channel before <|message|> content, returns empty content dict."""
current = "<|channel|>final\n"
result = parser.extract_tool_calls_streaming("", current, current)
# In final channel but no <|message|> yet
assert result == {"content": ""}
def test_final_channel_control_tokens_suppressed(self, parser):
"""Control tokens are suppressed; only clean text is emitted."""
# Simulate receiving <|return|> at end of final channel
prev = "<|channel|>final\n<|message|>Done."
current = prev + "<|return|>"
result = parser.extract_tool_calls_streaming(prev, current, "<|return|>")
# <|return|> should be stripped -- no new content
# The result should be empty content or no new content
if result is not None:
assert result.get("content", "") == ""
def test_call_in_delta_triggers_extraction(self, parser):
"""<|call|> in delta triggers full extraction."""
current = (
"<|channel|>commentary to=functions.add\n"
"<|constrain|>json\n"
'<|message|>{"a": 1, "b": 2}\n'
"<|call|>"
)
prev = current[: -len("<|call|>")]
result = parser.extract_tool_calls_streaming(prev, current, "<|call|>")
assert result is not None
assert "tool_calls" in result
tc = result["tool_calls"][0]
assert tc["function"]["name"] == "add"
assert tc["index"] == 0
assert tc["type"] == "function"
assert "id" in tc
def test_no_channel_markers_pass_through(self, parser):
"""Text with no channel markers passes through as content."""
result = parser.extract_tool_calls_streaming("", "Hello world", "Hello world")
assert result == {"content": "Hello world"}