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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
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
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
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
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
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
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
import inspect
import re
from typing import Dict, List, Optional, Tuple, Type

from sglang.srt.entrypoints.openai.protocol import ChatCompletionRequest
from sglang.srt.function_call.hunyuan_detector import resolve_hunyuan_tokens
from sglang.srt.parser.harmony_parser import HarmonyParser
from sglang.srt.parser.inkling_tokenizer import (
    CONTENT_INVOKE_TOOL_JSON,
    CONTENT_MODEL_END_SAMPLING,
    CONTENT_TEXT,
    CONTENT_THINKING,
    END_MESSAGE,
    INKLING_CONTROL_TOKENS,
    MESSAGE_MODEL,
)


class StreamingParseResult:
    """Result of streaming incremental parsing."""

    def __init__(
        self,
        normal_text: Optional[str] = None,
        reasoning_text: Optional[str] = None,
    ):
        self.normal_text = normal_text or ""
        self.reasoning_text = reasoning_text or ""


class BaseReasoningFormatDetector:
    """Base class providing two sets of interfaces: one-time and streaming incremental."""

    def __init__(
        self,
        think_start_token: str,
        think_end_token: str,
        think_excluded_tokens: Optional[List[str]] = None,
        force_reasoning: bool = False,
        stream_reasoning: bool = True,
        tool_start_token: Optional[str] = None,
        continue_final_message: bool = False,
        previous_content: str = "",
        thinks_internally: bool = False,
        reasoning_default: str = "always",
        force_nonempty_content: bool = False,
    ):
        self.think_start_token = think_start_token
        self.think_end_token = think_end_token
        self.think_excluded_tokens = think_excluded_tokens
        self.tool_start_token = tool_start_token
        self.force_reasoning = force_reasoning
        self._in_reasoning = force_reasoning
        self.stream_reasoning = stream_reasoning
        self.thinks_internally = thinks_internally
        self.reasoning_default = reasoning_default

        self._buffer = ""
        self.stripped_think_start = False
        self.think_start_self_label = ""

        self._force_nonempty_content = force_nonempty_content
        self._accumulated_reasoning = ""

        self.continue_final_message = continue_final_message
        if self.continue_final_message:
            self.previous_content = previous_content
            self.previous_count = len(previous_content)
        else:
            self.previous_content = ""
            self.previous_count = 0

        if self.think_start_token in self.previous_content:
            self._in_reasoning = True
        if self.think_end_token in self.previous_content:
            self._in_reasoning = False

    def _maybe_apply_force_nonempty_content(
        self, ret: StreamingParseResult
    ) -> StreamingParseResult:
        if self._force_nonempty_content and not ret.normal_text:
            ret.normal_text, ret.reasoning_text = ret.reasoning_text, ret.normal_text
        return ret

    def detect_and_parse(self, text: str) -> StreamingParseResult:
        """
        One-time parsing: Detects and parses reasoning sections in the provided text.
        Returns both reasoning content and normal text separately.
        """
        return self._maybe_apply_force_nonempty_content(
            self._detect_and_parse_impl(text)
        )

    def _detect_and_parse_impl(self, text: str) -> StreamingParseResult:
        in_reasoning = self._in_reasoning or self.think_start_token in text

        if not in_reasoning:
            return StreamingParseResult(normal_text=text)

        # The text is considered to be in a reasoning block.
        think_start_text = self.think_start_token + self.think_start_self_label
        processed_text = text
        while processed_text.startswith(think_start_text):
            processed_text = processed_text[len(think_start_text) :]

        if (
            self.think_end_token not in processed_text
            and self.think_end_token not in self.previous_content
        ):
            # Check for tool_start_token interruption
            if (
                in_reasoning
                and self.tool_start_token is not None
                and self.tool_start_token in processed_text
            ):
                # Find the first occurrence of tool_start_token and split there
                tool_idx = processed_text.find(self.tool_start_token)
                reasoning_text = processed_text[:tool_idx]
                # Preserve tool_start_token in normal text
                normal_text = processed_text[tool_idx:]
                return StreamingParseResult(
                    normal_text=normal_text, reasoning_text=reasoning_text
                )
            # Assume reasoning was truncated before end token
            return StreamingParseResult(reasoning_text=processed_text)

        # Extract reasoning content
        if self.think_end_token in processed_text:
            splits = processed_text.split(self.think_end_token, maxsplit=1)
            reasoning_text = splits[0]
            normal_text = splits[1]

            return StreamingParseResult(
                normal_text=normal_text, reasoning_text=reasoning_text
            )
        else:
            # think_end_token is in self.previous_content for continue_final_message=True case
            return StreamingParseResult(normal_text=processed_text)

    def parse_streaming_increment(self, new_text: str) -> StreamingParseResult:
        """
        Streaming incremental parsing for reasoning content.
        Handles partial reasoning tags and content.

        If stream_reasoning is False:
            Accumulates reasoning content until the end tag is found
        If stream_reasoning is True:
            Streams reasoning content as it arrives
        """
        ret = self._parse_streaming_increment_impl(new_text)
        if self._force_nonempty_content:
            if self._in_reasoning:
                self._accumulated_reasoning += ret.reasoning_text
            else:
                self._accumulated_reasoning = ""
        return ret

    def _parse_streaming_increment_impl(self, new_text: str) -> StreamingParseResult:
        self._buffer += new_text
        current_text = self._buffer

        think_start_text = self.think_start_token + self.think_start_self_label

        # If the current text is a prefix of the think token, keep buffering
        tokens_to_check = [think_start_text, self.think_end_token]
        if self.tool_start_token:
            tokens_to_check.append(self.tool_start_token)
        if any(
            token.startswith(current_text) and token != current_text
            for token in tokens_to_check
        ):
            return StreamingParseResult()

        # Strip `<think>` token if present
        if not self.stripped_think_start and think_start_text in current_text:
            current_text = current_text.replace(think_start_text, "", 1)
            self.stripped_think_start = True
            self._in_reasoning = True

        # Handle end of reasoning block
        if self._in_reasoning and self.think_end_token in current_text:
            end_idx = current_text.find(self.think_end_token)

            reasoning_text = current_text[:end_idx]

            self._buffer = ""
            self._in_reasoning = False
            normal_text = current_text[end_idx + len(self.think_end_token) :]

            return StreamingParseResult(
                normal_text=normal_text, reasoning_text=reasoning_text
            )

        # Continue with reasoning content
        if self._in_reasoning:
            # Check for tool_start_token interruption
            if self.tool_start_token and self.tool_start_token in current_text:
                tool_idx = current_text.find(self.tool_start_token)
                reasoning_text = current_text[:tool_idx]
                # Preserve tool_start_token in normal text
                normal_text = current_text[tool_idx:]
                self._buffer = ""
                self._in_reasoning = False
                return StreamingParseResult(
                    normal_text=normal_text, reasoning_text=reasoning_text
                )
            if self.stream_reasoning:
                # Stream the content immediately
                self._buffer = ""
                return StreamingParseResult(reasoning_text=current_text)
            else:
                return StreamingParseResult()

        # If we're not in a reasoning block return as normal text
        if not self._in_reasoning:
            self._buffer = ""
            return StreamingParseResult(normal_text=current_text)

        return StreamingParseResult()

    def finish(self) -> StreamingParseResult:
        """
        Called once when the stream ends. If force_nonempty_content is set
        and the stream ended mid-reasoning, reclassifies the accumulated
        reasoning (plus any partial token still buffered) as normal text.
        """
        if self._force_nonempty_content and self._in_reasoning:
            # stream_reasoning=False never clears _buffer, so the opening think
            # token (stripped only from the base class's local view) survives here.
            buffer = self._buffer
            think_start_text = self.think_start_token + self.think_start_self_label
            if buffer.startswith(think_start_text):
                buffer = buffer[len(think_start_text) :]
            normal_text = self._accumulated_reasoning + buffer
            self._accumulated_reasoning = ""
            self._buffer = ""
            if normal_text:
                return StreamingParseResult(normal_text=normal_text)
        return StreamingParseResult()


class DeepSeekR1Detector(BaseReasoningFormatDetector):
    """
    Detector for DeepSeek-R1 model.
    Assumes reasoning format:
      (<think>)*(.*)</think>
    Returns all the text before the </think> tag as `reasoning_text`
    and the rest of the text as `normal_text`.

    Supported models:
      - DeepSeek-R1: Always generates thinking content without <think> start tag
      - DeepSeek-R1-0528: Generates thinking content with <think> start tag

    Format patterns:
      - DeepSeek-R1: "I need to think about this...</think>The answer is 42."
      - DeepSeek-R1-0528: "<think>I need to think about this...</think>The answer is 42."

    Args:
        stream_reasoning (bool): If False, accumulates reasoning content until the end tag.
            If True, streams reasoning content as it arrives.
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = True,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        # DeepSeek-R1 is assumed to be reasoning until `</think>` token
        super().__init__(
            "<think>",
            "</think>",
            force_reasoning=True,
            stream_reasoning=stream_reasoning,
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            force_nonempty_content=force_nonempty_content,
        )
        # https://github.com/sgl-project/sglang/pull/3202#discussion_r1950153599


class Qwen3Detector(BaseReasoningFormatDetector):
    """
    Detector for Qwen3 models (e.g., Qwen/Qwen3-235B-A22B).
    Assumes reasoning format:
      (<think>)*(.*)</think>

    Qwen3 models released before 07/2025 supports switching between thinking mode and normal
    mode using `enable_thinking` parameter in the request parameter.
      - enable_thinking=True: "<think>reasoning content</think>The answer is 42."
      - enable_thinking=False: "The answer is 42." (no thinking tokens)

    Args:
        stream_reasoning (bool): If False, accumulates reasoning content until the end tag.
            If True, streams reasoning content as it arrives.
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        think_excluded_tokens = [
            "<tool_call>",
            "</tool_call>",
            "<|im_end|>",
            "<|endoftext|>",
        ]
        super().__init__(
            "<think>",
            "</think>",
            think_excluded_tokens=think_excluded_tokens,
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            # Qwen3.5 sometimes opens ``<tool_call>`` without closing
            # ``</think>``; treat it as an implicit reasoning close.
            tool_start_token="<tool_call>",
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            thinks_internally=True,
            reasoning_default="enable_thinking",
            force_nonempty_content=force_nonempty_content,
        )


class KimiDetector(BaseReasoningFormatDetector):
    """
    Detector for Kimi Thinking model.
    Assumes reasoning format:
      ◁think▷*(.*)◁/think▷
    Returns all the text before the ◁/think▷ tag as `reasoning_text`
    and the rest of the text as `normal_text`.
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        super().__init__(
            "◁think▷",
            "◁/think▷",
            force_reasoning=False,
            stream_reasoning=stream_reasoning,
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            force_nonempty_content=force_nonempty_content,
        )


class KimiK2Detector(BaseReasoningFormatDetector):
    """
    Detector for Kimi K2 models.
    Assumes reasoning format:
      (<think>)*(.*)</think>

    Kimi K2 can switch from reasoning to tool-call section with
    `<|tool_calls_section_begin|>` before emitting `</think>`.
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        think_excluded_tokens = [
            "<think>",
            "<|tool_calls_section_begin|>",
            "<|tool_call_begin|>",
            "<|tool_call_argument_begin|>",
            "<|tool_call_section_end|>",
            "<|tool_call_end|>",
            "[EOS]",
            "<|im_end|>",
            "<|end_header_id|>",
            "[EOT]",
        ]
        super().__init__(
            "<think>",
            "</think>",
            think_excluded_tokens=think_excluded_tokens,
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            tool_start_token="<|tool_calls_section_begin|>",
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            reasoning_default="thinking",
            force_nonempty_content=force_nonempty_content,
        )


class Glm45Detector(BaseReasoningFormatDetector):
    """
    Detector for GLM-4.5 models.
    Assumes reasoning format:
      (<think>)*(.*)</think>

    GLM-4.5 uses `<tool_call>` as the tool start token to switch from reasoning mode to normal mode.

    Args:
        stream_reasoning (bool): If False, accumulates reasoning content until the end tag.
            If True, streams reasoning content as it arrives.
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        force_nonempty_content: bool = False,
    ):
        think_excluded_tokens = [
            "<tool_call>",
            "</tool_call>",
            "<eop>",
            "<|user|>",
            "<|endoftext|>",
        ]
        super().__init__(
            "<think>",
            "</think>",
            think_excluded_tokens=think_excluded_tokens,
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            tool_start_token="<tool_call>",
            thinks_internally=True,
            reasoning_default="enable_thinking",
            force_nonempty_content=force_nonempty_content,
        )


class GptOssDetector(BaseReasoningFormatDetector):
    """
    Detector for T4-style reasoning format (GPT-OSS), using the HarmonyParser.
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = True,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        super().__init__(
            "<|channel|>analysis<|message|>",
            "<|end|>",
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            force_nonempty_content=force_nonempty_content,
        )
        self.parser = HarmonyParser()

    def detect_and_parse(self, text: str) -> StreamingParseResult:
        events = self.parser.parse(text)
        # Flush the buffer for one-shot parsing
        events += self.parser.parse("")

        reasoning_text = "".join(
            [e.content for e in events if e.event_type == "reasoning"]
        )
        normal_parts = []
        for e in events:
            if e.event_type == "normal":
                normal_parts.append(e.content)
            elif e.event_type == "tool_call":
                # Use raw_text to preserve structural markers for function call detector
                normal_parts.append(e.raw_text if e.raw_text else e.content)
        normal_text = "".join(normal_parts)
        # Tool call events preserve raw text with structural markers

        return self._maybe_apply_force_nonempty_content(
            StreamingParseResult(
                normal_text=normal_text,
                reasoning_text=reasoning_text,
            )
        )

    def parse_streaming_increment(self, new_text: str) -> StreamingParseResult:
        events = self.parser.parse(new_text)

        reasoning_text = "".join(
            [e.content for e in events if e.event_type == "reasoning"]
        )
        normal_parts = []
        for e in events:
            if e.event_type == "normal":
                normal_parts.append(e.content)
            elif e.event_type == "tool_call":
                # Use raw_text to preserve structural markers for function call detector
                normal_parts.append(e.raw_text if e.raw_text else e.content)
        normal_text = "".join(normal_parts)

        return StreamingParseResult(
            normal_text=normal_text,
            reasoning_text=reasoning_text,
        )


class MiniMaxAppendThinkDetector(BaseReasoningFormatDetector):
    """
    Append `<think>` token to the beginning of the text.
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        # scheduler.py need `reasoning_parser.detector.think_end_token`
        super().__init__(
            "<think>",
            "</think>",
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            force_nonempty_content=force_nonempty_content,
        )
        self.is_first_chunk = False

    def parse_streaming_increment(self, new_text: str) -> StreamingParseResult:
        if not self.is_first_chunk:
            self.is_first_chunk = True
            new_text = self.think_start_token + new_text
        return StreamingParseResult(normal_text=new_text)

    def detect_and_parse(self, text: str) -> StreamingParseResult:
        return StreamingParseResult(normal_text=self.think_start_token + text)


class Nemotron3Detector(BaseReasoningFormatDetector):
    """
    Detector for Nemotron3 model.
    Uses the same reasoning format as DeepSeek-R1: (<think>)*(.*)</think>

    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        super().__init__(
            "<think>",
            "</think>",
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            tool_start_token="<tool_call>",
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            reasoning_default="enable_thinking",
            force_nonempty_content=force_nonempty_content,
        )


class MiniMaxM3Detector(BaseReasoningFormatDetector):
    """MiniMax-M3 detector. Format: (<mm:think>)*(.*)</mm:think>.

    In multi-turn chats M3 prefixes earlier non-thinking turns with a bare
    ``</mm:think>``, so a non-thinking reply may open with one stray closer; drop it unless thinking.
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        super().__init__(
            "<mm:think>",
            "</mm:think>",
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            continue_final_message=continue_final_message,
            previous_content=previous_content,
        )
        self._lead_buffer = ""
        self._checked_leading_close = False
        self._force_nonempty_content = force_nonempty_content

    def detect_and_parse(self, text: str) -> StreamingParseResult:
        if not self._in_reasoning and text.lstrip().startswith(self.think_end_token):
            text = text.lstrip()[len(self.think_end_token) :]
        ret = super().detect_and_parse(text)
        if self._force_nonempty_content and not ret.normal_text:
            ret.normal_text, ret.reasoning_text = ret.reasoning_text, ret.normal_text
        return ret

    def parse_streaming_increment(self, new_text: str) -> StreamingParseResult:
        # ``</mm:think>`` is a single token, so a stray leading closer arrives whole.
        if not self._checked_leading_close and not self._in_reasoning:
            self._lead_buffer += new_text
            stripped = self._lead_buffer.lstrip()
            if not stripped:
                return StreamingParseResult()
            self._checked_leading_close = True
            if stripped.startswith(self.think_end_token):
                new_text = stripped[len(self.think_end_token) :]
            else:
                new_text = self._lead_buffer
            self._lead_buffer = ""
            if not new_text:
                return StreamingParseResult()
        return super().parse_streaming_increment(new_text)


class MistralDetector(BaseReasoningFormatDetector):
    """
    Detector for Mistral models with reasoning (e.g., Mistral-Small-4-119B-2603).
    Assumes reasoning format:
      [THINK]reasoning content[/THINK]answer

    Reasoning is optional — it only appears when reasoning_effort="high" is set.
    When reasoning_effort="none", the model outputs directly without thinking tokens.
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        super().__init__(
            "[THINK]",
            "[/THINK]",
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            reasoning_default="mistral",
            force_nonempty_content=force_nonempty_content,
        )


class HunyuanDetector(BaseReasoningFormatDetector):
    """
    Detector for Hunyuan models (e.g., tencent/Hunyuan-A13B-Instruct).

    Like Glm45Detector but uses ``<tool_calls>`` (plural) as the tool start token.
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        tokenizer=None,
        force_nonempty_content: bool = False,
    ):
        t = resolve_hunyuan_tokens(tokenizer)
        think_open = t["think"]
        think_close = (
            "</" + think_open[1:] if think_open.startswith("<") else think_open
        )
        super().__init__(
            think_open,
            think_close,
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            tool_start_token=t["tool_calls"],
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            force_nonempty_content=force_nonempty_content,
        )


class Gemma4Detector(BaseReasoningFormatDetector):
    """Gemma4 reasoning detector."""

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        super().__init__(
            "<|channel>",
            "<channel|>",
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            reasoning_default="explicit_enable_thinking",
            force_nonempty_content=force_nonempty_content,
        )
        self.think_start_self_label = "thought\n"


_INKLING_CONTENT_KINDS = {
    CONTENT_THINKING: "reasoning",
    CONTENT_TEXT: "content",
}
_INKLING_END_TOKENS = {
    CONTENT_MODEL_END_SAMPLING,
    END_MESSAGE,
}
_INKLING_CONTROL_TOKENS = INKLING_CONTROL_TOKENS
_INKLING_CONTROL_RE = re.compile(
    "|".join(re.escape(t) for t in sorted(_INKLING_CONTROL_TOKENS))
)


class InklingDetector(BaseReasoningFormatDetector):
    """Detector for Inkling typed content blocks."""

    # Parse the model's sequence of typed content blocks, for example:
    #   <|message_model|><|content_thinking|>reasoning<|end_message|>
    #   <|message_model|><|content_text|>visible answer<|end_message|>
    #   <|content_model_end_sampling|>
    # Special tokens must decode literally so thinking and visible text can be
    # routed to their respective response fields.
    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        del force_nonempty_content
        super().__init__(
            CONTENT_THINKING,
            END_MESSAGE,
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            thinks_internally=False,
            reasoning_default="always",
        )

        self._kind: str | None = None
        self._pending_header = ""
        self._pending_reasoning = ""

    def detect_and_parse(self, text: str) -> StreamingParseResult:
        self._buffer = ""
        self._kind = None
        self._pending_header = ""
        self._pending_reasoning = ""
        ret = self._parse_blocks(text)
        if self._kind == "reasoning" and not self.stream_reasoning:
            ret.reasoning_text += self._pending_reasoning
        self._kind = None
        self._pending_header = ""
        self._pending_reasoning = ""
        return ret

    def parse_streaming_increment(self, new_text: str) -> StreamingParseResult:
        text = self._buffer + new_text
        partial_len = self._partial_control_length(text)
        if partial_len:
            self._buffer = text[-partial_len:]
            text = text[:-partial_len]
        else:
            self._buffer = ""
        return self._parse_blocks(text)

    def finish(self) -> StreamingParseResult:
        # Flush reasoning buffered under stream_reasoning=False when the stream
        # ends before a control/end token closes the block (e.g. max_tokens cut
        # a thinking block short). Mirrors the non-streaming flush in
        # detect_and_parse; without it the trailing reasoning trace is dropped.
        reasoning_text = ""
        if self._kind == "reasoning" and not self.stream_reasoning:
            reasoning_text = self._pending_reasoning
        self._buffer = ""
        self._pending_reasoning = ""
        self._pending_header = ""
        self._kind = None
        return StreamingParseResult(reasoning_text=reasoning_text)

    @staticmethod
    def _partial_control_length(text: str) -> int:
        max_token_len = max(map(len, _INKLING_CONTROL_TOKENS))
        for length in range(min(len(text), max_token_len - 1), 0, -1):
            suffix = text[-length:]
            if any(
                len(suffix) < len(token) and token.startswith(suffix)
                for token in _INKLING_CONTROL_TOKENS
            ):
                return length
        return 0

    def _parse_blocks(self, text: str) -> StreamingParseResult:
        reasoning: list[str] = []
        content: list[str] = []
        saw_control = False
        pos = 0

        def emit(text: str) -> None:
            if self._kind == "reasoning":
                if self.stream_reasoning:
                    reasoning.append(text)
                else:
                    self._pending_reasoning += text
            elif self._kind == "content":
                content.append(text)
            elif self._kind == "tool":
                content.append(text)
            elif self._kind == "header":
                self._pending_header += text
            elif text:
                # No open block — e.g. a continue_final_message stream resuming
                # mid text block. Route to visible content, matching the
                # no-control-token path below.
                content.append(text)

        def flush_reasoning() -> None:
            if self._kind == "reasoning" and not self.stream_reasoning:
                reasoning.append(self._pending_reasoning)
                self._pending_reasoning = ""

        for match in _INKLING_CONTROL_RE.finditer(text):
            saw_control = True
            emit(text[pos : match.start()])

            token = match.group(0)
            pos = match.end()
            if token == MESSAGE_MODEL:
                if self._kind in (None, "header"):
                    flush_reasoning()
                    self._pending_header = ""
                    self._kind = "header"
                else:
                    # Inside an open block a decoded <|message_model|> string
                    # is payload the model wrote (e.g. quoting the protocol) —
                    # a real header can only follow an end token. Preserve it
                    # instead of rerouting the rest of the block into a header.
                    emit(token)
            elif token == CONTENT_INVOKE_TOOL_JSON:
                flush_reasoning()
                if self._kind == "header":
                    content.extend(
                        (MESSAGE_MODEL, self._pending_header, CONTENT_INVOKE_TOOL_JSON)
                    )
                    self._pending_header = ""
                else:
                    content.append(token)
                self._kind = "tool"
            elif self._kind == "tool":
                content.append(token)
                if token in _INKLING_END_TOKENS:
                    self._kind = None
            elif token in _INKLING_CONTENT_KINDS:
                flush_reasoning()
                self._pending_header = ""
                self._kind = _INKLING_CONTENT_KINDS[token]
            elif token in _INKLING_END_TOKENS:
                flush_reasoning()
                self._pending_header = ""
                self._kind = None

        tail = text[pos:]
        if saw_control or self._kind is not None:
            emit(tail)
        else:
            content.append(text)

        return StreamingParseResult(
            normal_text="".join(content),
            reasoning_text="".join(reasoning),
        )


class _DeepSeekV3Detector(Qwen3Detector):
    """DeepSeek-V3 reuses Qwen3 tokens but requires explicit thinking=True to enable."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.reasoning_default = "explicit_thinking"


class _MimoDetector(Qwen3Detector):
    """MIMO reuses Qwen3 tokens but requires explicit enable_thinking=True to enable."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.reasoning_default = "explicit_enable_thinking"


class _PoolsideV1Detector(Qwen3Detector):
    """Poolside v1 (Laguna-XS.2) reuses Qwen3 <think> tokens but the HF chat template
    defaults `enable_thinking=False`; reasoning is opt-in via `enable_thinking=True`."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.reasoning_default = "explicit_enable_thinking"


class Apertus2509Detector(BaseReasoningFormatDetector):
    """
    Detector for Apertus 2509 models

    Reasoning blocks are delimited by:
        <|inner_prefix|> ... <|inner_suffix|>
    """

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = False,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        super().__init__(
            "<|inner_prefix|>",
            "<|inner_suffix|>",
            force_reasoning=False,
            stream_reasoning=stream_reasoning,
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            force_nonempty_content=force_nonempty_content,
        )
        self._force_reasoning = force_reasoning
        self._tool_start_token = "<|tools_prefix|>["
        self._tool_end_token = "<|tools_suffix|>"
        self._reasoning_acc: str = ""
        self._in_inner_tool: bool = False

    @staticmethod
    def _ends_with_partial_token(buffer: str, token: str) -> int:
        for i in range(1, min(len(buffer) + 1, len(token))):
            if token.startswith(buffer[-i:]):
                return i
        return 0

    def detect_and_parse(self, text: str) -> StreamingParseResult:
        blocks = self.detect_and_parse_block_sequence(text)
        reasoning_parts = [t for k, t in blocks if k == "reasoning"]
        text_parts = [t for k, t in blocks if k == "text"]
        ret = StreamingParseResult(
            normal_text="".join(text_parts),
            reasoning_text="".join(reasoning_parts),
        )
        return self._maybe_apply_force_nonempty_content(ret)

    def detect_and_parse_block_sequence(self, text: str) -> list[tuple[str, str]]:
        """Return an ordered sequence of blocks: [("reasoning"|"text", content), ...]"""
        start_tok = self.think_start_token
        end_tok = self.think_end_token
        blocks: list[tuple[str, str]] = []
        cursor = 0

        # continue_final_message can resume inside an existing inner
        if self._in_reasoning:
            if (e := text.find(end_tok, cursor)) == -1:
                blocks.extend(self._split_inner_reasoning(text[cursor:]))
                blocks.append(("text", ""))
                return blocks
            blocks.extend(self._split_inner_reasoning(text[cursor:e]))
            cursor = e + len(end_tok)

        while True:
            if (s := text.find(start_tok, cursor)) == -1:
                # Always include the trailing text block (may be empty)
                blocks.append(("text", text[cursor:]))
                break
            if s > cursor:
                blocks.append(("text", text[cursor:s]))

            cursor = s + len(start_tok)
            if (e := text.find(end_tok, cursor)) == -1:
                blocks.extend(self._split_inner_reasoning(text[cursor:]))
                blocks.append(("text", ""))
                break
            blocks.extend(self._split_inner_reasoning(text[cursor:e]))
            cursor = e + len(end_tok)

        last_idx = len(blocks) - 1
        blocks = [
            (k, t)
            for i, (k, t) in enumerate(blocks)
            if not (k == "text" and t == "" and i != last_idx)
        ]

        return blocks

    def _split_inner_reasoning(self, inner_text: str) -> list[tuple[str, str]]:
        """
        Split content inside <|inner_prefix|>...<|inner_suffix|> into:
          - ("reasoning", <thoughts text>)
          - ("text", <|tools_prefix|>[...]<|tools_suffix|>) for any tool calls inside reasoning
        """
        tool_start = self._tool_start_token
        tool_end = self._tool_end_token
        out: list[tuple[str, str]] = []
        cursor = 0

        while True:
            if (s := inner_text.find(tool_start, cursor)) == -1:
                if (tail := inner_text[cursor:]) != "":
                    out.append(("reasoning", tail))
                break
            if s > cursor:
                out.append(("reasoning", inner_text[cursor:s]))

            if (e := inner_text.find(tool_end, s)) == -1:
                out.append(("text", inner_text[s:]))
                break

            out.append(("text", inner_text[s : e + len(tool_end)]))
            cursor = e + len(tool_end)

        return out

    def parse_streaming_increment(self, new_text: str) -> StreamingParseResult:
        self._buffer += new_text

        out_reasoning = ""
        out_normal = ""

        start_tok = self.think_start_token
        end_tok = self.think_end_token
        tool_start = self._tool_start_token
        tool_end = self._tool_end_token

        while True:
            if not self._in_reasoning:
                if (s := self._buffer.find(start_tok)) == -1:
                    if partial := self._ends_with_partial_token(
                        self._buffer, start_tok
                    ):
                        out_normal += self._buffer[:-partial]
                        self._buffer = self._buffer[-partial:]
                    else:
                        out_normal += self._buffer
                        self._buffer = ""
                    return StreamingParseResult(
                        normal_text=out_normal, reasoning_text=out_reasoning
                    )

                out_normal += self._buffer[:s]
                self._buffer = self._buffer[s + len(start_tok) :]
                self._in_reasoning = True
                self._reasoning_acc = ""
                self._in_inner_tool = False
                continue

            if self._in_inner_tool:
                if (end_pos := self._buffer.find(tool_end)) == -1:
                    if (
                        hold := self._ends_with_partial_token(self._buffer, tool_end)
                    ) != 0:
                        out_normal += self._buffer[:-hold]
                        self._buffer = self._buffer[-hold:]
                    else:
                        out_normal += self._buffer
                        self._buffer = ""
                    return StreamingParseResult(
                        normal_text=out_normal, reasoning_text=out_reasoning
                    )

                out_normal += self._buffer[: end_pos + len(tool_end)]
                self._buffer = self._buffer[end_pos + len(tool_end) :]
                self._in_inner_tool = False
                continue

            pos_tool = self._buffer.find(tool_start)
            pos_end = self._buffer.find(end_tok)

            if pos_tool == -1 and pos_end == -1:
                if self.stream_reasoning:
                    if (
                        hold := max(
                            self._ends_with_partial_token(self._buffer, end_tok),
                            self._ends_with_partial_token(self._buffer, tool_start),
                        )
                    ) != 0:
                        out_reasoning += self._buffer[:-hold]
                        self._buffer = self._buffer[-hold:]
                    else:
                        out_reasoning += self._buffer
                        self._buffer = ""
                return StreamingParseResult(
                    normal_text=out_normal, reasoning_text=out_reasoning
                )

            next_pos = min(p for p in [pos_tool, pos_end] if p != -1)

            if pos_end != -1 and pos_end == next_pos:
                reasoning_chunk = self._buffer[:pos_end]
                if self.stream_reasoning:
                    out_reasoning += reasoning_chunk
                else:
                    self._reasoning_acc += reasoning_chunk
                    out_reasoning += self._reasoning_acc
                    self._reasoning_acc = ""
                self._buffer = self._buffer[pos_end + len(end_tok) :]
                self._in_reasoning = False
                continue

            reasoning_chunk = self._buffer[:pos_tool]
            if self.stream_reasoning:
                out_reasoning += reasoning_chunk
            else:
                self._reasoning_acc += reasoning_chunk
            self._buffer = self._buffer[pos_tool:]
            self._in_inner_tool = True
            continue


class CohereCommand4Detector(BaseReasoningFormatDetector):
    """Detector for Cohere Command4 / Command-A family (incl. cohere2_moe and
    cohere2_vision Command-A-Plus).

    Generated format (the assistant prefix in the chat template already emits
    ``<|START_THINKING|>`` when ``reasoning=True``, so the *generated* text
    typically begins inside the thinking block):

        thinking_content<|END_THINKING|><|START_TEXT|>final_answer<|END_TEXT|>

    When ``reasoning=False`` the chat template emits both START/END_THINKING
    in the prefix and the generated text is just::

        <|START_TEXT|>final_answer<|END_TEXT|>

    This detector returns:
      - ``reasoning_text`` = the thinking block (between START_THINKING and
        END_THINKING, with the START tag stripped if the model echoed it).
      - ``normal_text`` = the content between ``<|START_TEXT|>`` and
        ``<|END_TEXT|>``, with both markers stripped. If no ``<|START_TEXT|>``
        appears (the model exhausted max_new_tokens still inside thinking),
        ``normal_text`` is the empty string.

    Matches the public token names from the model's
    ``special_tokens_map.json`` (``<|START_THINKING|>`` etc.).
    """

    TEXT_START_TOKEN = "<|START_TEXT|>"
    TEXT_END_TOKEN = "<|END_TEXT|>"
    # When the model decides to call tools instead of producing a final text
    # block, it emits an action block instead of a text block. The reasoning
    # parser must leave that block intact so the downstream tool-call parser
    # can pick it up.
    ACTION_START_TOKEN = "<|START_ACTION|>"

    def __init__(
        self,
        stream_reasoning: bool = True,
        force_reasoning: bool = True,
        continue_final_message: bool = False,
        previous_content: str = "",
        force_nonempty_content: bool = False,
    ):
        # The chat template puts <|START_THINKING|> in the assistant prefix
        # when reasoning is enabled, so the *generated* text usually starts
        # already inside thinking. ``force_reasoning=True`` makes the base
        # detector treat the leading bytes as reasoning even though the
        # generated stream typically does not echo <|START_THINKING|>.
        super().__init__(
            think_start_token="<|START_THINKING|>",
            think_end_token="<|END_THINKING|>",
            force_reasoning=force_reasoning,
            stream_reasoning=stream_reasoning,
            continue_final_message=continue_final_message,
            previous_content=previous_content,
            force_nonempty_content=force_nonempty_content,
        )
        # Streaming state machine. The model emits, in order:
        #   1. reasoning  (between START_THINKING [in prefix] and END_THINKING)
        #   2. either ``<|START_TEXT|>...<|END_TEXT|>`` (final answer) or
        #      ``<|START_ACTION|>...<|END_ACTION|>`` (tool calls) -- never both.
        # When ``reasoning=False`` the chat template emits both START/END
        # thinking in the prefix and step 1 is empty; the generated stream
        # then starts directly with the text or action block.
        self._reasoning_done = False
        self._saw_text_start = False
        self._saw_text_end = False
        self._in_action_mode = False

    @classmethod
    def _strip_text_markers(cls, raw: str) -> str:
        """Extract the substring between ``<|START_TEXT|>`` and
        ``<|END_TEXT|>``. If ``<|START_TEXT|>`` is absent but a
        ``<|START_ACTION|>`` block is present, the model produced a tool
        call instead of a text answer -- return the raw text untouched so
        the downstream tool-call parser can pick up the action block. If
        neither marker is present (ran out of tokens still inside
        thinking) return ``""``. If ``<|END_TEXT|>`` is absent (stop token
        or max_new_tokens cut the stream off inside the text block) return
        everything after ``<|START_TEXT|>``.
        """
        if not raw:
            return ""
        s = raw.find(cls.TEXT_START_TOKEN)
        if s == -1:
            if cls.ACTION_START_TOKEN in raw:
                return raw
            return ""
        s += len(cls.TEXT_START_TOKEN)
        tail = raw[s:]
        e = tail.find(cls.TEXT_END_TOKEN)
        if e == -1:
            return tail
        return tail[:e]

    def detect_and_parse(self, text: str) -> StreamingParseResult:
        # Direct parse: split on the (single) ``<|END_THINKING|>`` token if
        # present. Anything before is reasoning, anything after is the
        # final-text block. If no END_THINKING but a START_TEXT exists,
        # we're in the reasoning=False case (chat template emitted both
        # START/END thinking in the prefix; the model only generated the
        # text block). Otherwise the model exhausted tokens still thinking
        # and ``normal_text`` ends up empty -- matching the convention of
        # the other detectors in this module (DeepSeekR1, Qwen3, ...). The
        # empty content is propagated as ``message.content = None`` by
        # serving_chat, and downstream code is expected to treat that as
        # "no answer" rather than falling back to ``reasoning_content``.
        end_think_idx = text.find(self.think_end_token)
        text_start_idx = text.find(self.TEXT_START_TOKEN)
        action_start_idx = text.find(self.ACTION_START_TOKEN)
        if end_think_idx != -1:
            reasoning = text[:end_think_idx]
            rest = text[end_think_idx + len(self.think_end_token) :]
        elif text_start_idx != -1:
            reasoning = text[:text_start_idx]
            rest = text[text_start_idx:]
        elif action_start_idx != -1:
            # reasoning=False + tool call: chat template emitted both
            # START/END thinking in the prefix, the model only generated
            # an action block. Treat the prefix before the action block as
            # (probably empty) reasoning so the action block reaches the
            # tool-call parser intact.
            reasoning = text[:action_start_idx]
            rest = text[action_start_idx:]
        else:
            reasoning = text
            rest = ""

        # Some checkpoints echo the START_THINKING token even though the
        # chat template put it in the prefix; drop it if so.
        think_start_text = self.think_start_token + self.think_start_self_label
        if reasoning.startswith(think_start_text):
            reasoning = reasoning[len(think_start_text) :]

        return self._maybe_apply_force_nonempty_content(
            StreamingParseResult(
                normal_text=self._strip_text_markers(rest),
                reasoning_text=reasoning,
            )
        )

    def parse_streaming_increment(self, new_text: str) -> StreamingParseResult:
        """Streaming parse. Custom state machine -- we don't reuse the base
        class because Cohere's "reasoning=False" path (the model emits no
        ``<|END_THINKING|>``, just goes straight to a text or action block)
        is fundamentally incompatible with the base detector's
        ``force_reasoning`` semantics."""
        self._buffer += new_text
        buf = self._buffer

        if not self._reasoning_done:
            # Look for any marker that ends reasoning: an explicit
            # END_THINKING, or an implicit transition via the start of the
            # final-text or action block (reasoning=False case).
            markers = (
                (self.think_end_token, "think_end"),
                (self.TEXT_START_TOKEN, "text"),
                (self.ACTION_START_TOKEN, "action"),
            )
            first_pos = None
            first_marker = None
            first_kind = None
            for marker_text, kind in markers:
                p = buf.find(marker_text)
                if p != -1 and (first_pos is None or p < first_pos):
                    first_pos, first_marker, first_kind = p, marker_text, kind
            if first_pos is None:
                # No marker seen yet. Stream the reasoning prefix, but keep
                # enough tail in the buffer to recognise a marker split
                # across chunk boundaries.
                if not self.stream_reasoning:
                    return StreamingParseResult()
                max_keep = max(len(m) for m, _ in markers) - 1
                if len(buf) > max_keep:
                    head = buf[:-max_keep]
                    self._buffer = buf[-max_keep:]
                    return StreamingParseResult(reasoning_text=head)
                return StreamingParseResult()

            reasoning_chunk = buf[:first_pos]
            if first_kind == "think_end":
                self._buffer = buf[first_pos + len(first_marker) :]
            else:
                # Implicit reasoning-end: leave the start-of-block marker in
                # the buffer for the post-thinking branch below to consume.
                self._buffer = buf[first_pos:]
            self._reasoning_done = True
            if reasoning_chunk:
                return StreamingParseResult(reasoning_text=reasoning_chunk)
            buf = self._buffer

        # Reasoning is closed. Decide between text-stripping and
        # action-passthrough on first sight of a marker.
        if self._in_action_mode:
            if not buf:
                return StreamingParseResult()
            self._buffer = ""
            return StreamingParseResult(normal_text=buf)

        if not self._saw_text_start:
            s_text = buf.find(self.TEXT_START_TOKEN)
            s_action = buf.find(self.ACTION_START_TOKEN)
            picks = [
                (p, k) for p, k in ((s_text, "text"), (s_action, "action")) if p != -1
            ]
            if not picks:
                max_keep = (
                    max(len(self.TEXT_START_TOKEN), len(self.ACTION_START_TOKEN)) - 1
                )
                if len(buf) > max_keep:
                    self._buffer = buf[-max_keep:]
                return StreamingParseResult()
            picks.sort()
            first_pos, first_kind = picks[0]
            if first_kind == "action":
                self._in_action_mode = True
                out_normal = buf[first_pos:]
                self._buffer = ""
                return StreamingParseResult(normal_text=out_normal)
            # Found <|START_TEXT|>. Drop everything up to and including the
            # marker -- text content streams next.
            self._buffer = buf[first_pos + len(self.TEXT_START_TOKEN) :]
            self._saw_text_start = True
            buf = self._buffer

        if self._saw_text_start and not self._saw_text_end:
            e = buf.find(self.TEXT_END_TOKEN)
            if e == -1:
                # Emit everything except a possible partial END_TEXT tail.
                keep = len(self.TEXT_END_TOKEN) - 1
                if len(buf) > keep:
                    out_normal = buf[:-keep]
                    self._buffer = buf[-keep:]
                    return StreamingParseResult(normal_text=out_normal)
                return StreamingParseResult()
            out_normal = buf[:e]
            self._buffer = buf[e + len(self.TEXT_END_TOKEN) :]
            self._saw_text_end = True
            return StreamingParseResult(normal_text=out_normal)

        return StreamingParseResult()


class ReasoningParser:
    """
    Parser that handles both streaming and non-streaming scenarios for extracting
    reasoning content from model outputs.

    Args:
        model_type (str): Type of model to parse reasoning from
        stream_reasoning (bool): If False, accumulates reasoning content until complete.
            If True, streams reasoning content as it arrives.
    """

    DetectorMap: Dict[str, Type[BaseReasoningFormatDetector]] = {
        "apertus2509": Apertus2509Detector,
        "deepseek-r1": DeepSeekR1Detector,
        "deepseek-v3": _DeepSeekV3Detector,
        "agnes": _DeepSeekV3Detector,  # alias: Agnes uses the deepseek-v4 format
        "deepseek-v4": _DeepSeekV3Detector,
        "glm45": Glm45Detector,
        "hunyuan": HunyuanDetector,
        "gpt-oss": GptOssDetector,
        "kimi": KimiDetector,
        "kimi_k2": KimiK2Detector,
        "mimo": _MimoDetector,
        "poolside_v1": _PoolsideV1Detector,
        "qwen3": Qwen3Detector,
        "qwen3-thinking": Qwen3Detector,
        "minimax": Qwen3Detector,
        "minimax-append-think": MiniMaxAppendThinkDetector,
        "minimax-m3": MiniMaxM3Detector,
        "step3": DeepSeekR1Detector,
        "step3p5": DeepSeekR1Detector,
        "mistral": MistralDetector,
        "nemotron_3": Nemotron3Detector,
        "interns1": Qwen3Detector,
        "gemma4": Gemma4Detector,
        "inkling": InklingDetector,
        "cohere_command4": CohereCommand4Detector,
    }

    def __init__(
        self,
        model_type: Optional[str] = None,
        stream_reasoning: bool = True,
        force_reasoning: Optional[bool] = None,
        request: ChatCompletionRequest = None,
        tokenizer=None,
    ):
        if not model_type:
            raise ValueError("Model type must be specified")

        detector_class = self.DetectorMap.get(model_type.lower())
        if not detector_class:
            raise ValueError(f"Unsupported model type: {model_type}")

        chat_template_kwargs = getattr(request, "chat_template_kwargs", None) or {}

        # Special cases where we override force_reasoning
        if model_type.lower() in {
            "qwen3-thinking",
            "gpt-oss",
            "minimax",
        }:
            force_reasoning = True

        # M3 consumes the <mm:think> start tag only for thinking_mode=enabled
        # (absent from output → must force); mirror serving_chat's M3 branch.
        if model_type.lower() == "minimax-m3" and force_reasoning is None:
            force_reasoning = chat_template_kwargs.get("thinking_mode") == "enabled"

        # Only pass force_reasoning if explicitly set, let detectors use their defaults
        kwargs = {"stream_reasoning": stream_reasoning}
        if force_reasoning is not None:
            kwargs["force_reasoning"] = force_reasoning

        if (
            request is not None
            and isinstance(request, ChatCompletionRequest)
            and request.continue_final_message
            and request.messages[-1].role == "assistant"
        ):
            kwargs["continue_final_message"] = True
            kwargs["previous_content"] = request.messages[-1].content

        if chat_template_kwargs.get("force_nonempty_content") is True:
            kwargs["force_nonempty_content"] = True

        if tokenizer is not None:
            sig = inspect.signature(detector_class)
            if "tokenizer" in sig.parameters:
                kwargs["tokenizer"] = tokenizer

        self.detector = detector_class(**kwargs)

    def parse_non_stream(self, full_text: str) -> Tuple[Optional[str], Optional[str]]:
        """Non-streaming call: one-time parsing"""
        ret = self.detector.detect_and_parse(full_text)
        return ret.reasoning_text, ret.normal_text

    def parse_non_stream_blocks(self, full_text: str) -> list[dict]:
        """Non-streaming call: return an ordered sequence of reasoning/text blocks"""
        if hasattr(self.detector, "detect_and_parse_block_sequence"):
            seq = self.detector.detect_and_parse_block_sequence(full_text)
            return [{"type": k, "text": t} for k, t in seq]

        ret = self.detector.detect_and_parse(full_text)
        blocks: list[dict] = []
        if ret.reasoning_text:
            blocks.append({"type": "reasoning", "text": ret.reasoning_text})
        blocks.append({"type": "text", "text": ret.normal_text or ""})
        return blocks

    def parse_stream_chunk(
        self, chunk_text: str
    ) -> Tuple[Optional[str], Optional[str]]:
        """Streaming call: incremental parsing"""
        ret = self.detector.parse_streaming_increment(chunk_text)
        return ret.reasoning_text, ret.normal_text

    def parse_stream_end(self) -> Tuple[Optional[str], Optional[str]]:
        """Streaming call: flush any detector-specific buffered state once
        the stream ends."""
        ret = self.detector.finish()
        return ret.reasoning_text, ret.normal_text