@@ -155,6 +155,30 @@ export const make_api_request = async (params: {
155155 processed_think_content_length =
156156 start_match . index ! + start_match [ 0 ] . length
157157 } else {
158+ const think_end_regex = / < \/ ( t h i n k | t h o u g h t ) > /
159+ const end_match = full_response . match ( think_end_regex )
160+
161+ if ( end_match ) {
162+ const think_content_chunk = full_response . substring (
163+ 0 ,
164+ end_match . index !
165+ )
166+ if ( think_content_chunk ) {
167+ handle_thinking_chunk ( think_content_chunk )
168+ }
169+
170+ think_block_closed = true
171+
172+ const content_after = full_response . substring (
173+ end_match . index ! + end_match [ 0 ] . length
174+ )
175+ content_for_client = content_after
176+ if ( content_after ) {
177+ handle_chunk_metrics ( content_after )
178+ }
179+ return
180+ }
181+
158182 const trimmed_response = full_response . trimStart ( )
159183 if ( trimmed_response . length == 0 ) {
160184 return
@@ -281,7 +305,27 @@ export const make_api_request = async (params: {
281305 const thoughts_match = full_response . match (
282306 / < (?: t h i n k | t h o u g h t ) > ( [ \s \S ] * ?) < \/ (?: t h i n k | t h o u g h t ) > /
283307 )
284- const thoughts = thoughts_match ? thoughts_match [ 1 ] . trim ( ) : undefined
308+ let thoughts = thoughts_match ? thoughts_match [ 1 ] . trim ( ) : undefined
309+ let final_content = content_for_client
310+
311+ if ( ! thoughts_match ) {
312+ const end_match = full_response . match ( / < \/ (?: t h i n k | t h o u g h t ) > / )
313+ if ( end_match ) {
314+ const start_match = full_response . match ( / < (?: t h i n k | t h o u g h t ) > / )
315+ if ( ! start_match ) {
316+ thoughts = full_response . substring ( 0 , end_match . index ) . trim ( )
317+ final_content = full_response
318+ . substring ( end_match . index ! + end_match [ 0 ] . length )
319+ . trim ( )
320+ Logger . info ( {
321+ function_name : 'make_api_request' ,
322+ message :
323+ 'Detected closing tag without opening tag, stripped content before </think>' ,
324+ data : { thoughts : 'xxx' }
325+ } )
326+ }
327+ }
328+ }
285329
286330 Logger . info ( {
287331 function_name : 'make_api_request' ,
@@ -296,7 +340,7 @@ export const make_api_request = async (params: {
296340 } )
297341 }
298342
299- resolve ( { response : content_for_client , thoughts } )
343+ resolve ( { response : final_content , thoughts } )
300344 } )
301345
302346 response . data . on ( 'error' , ( error : Error ) => {
0 commit comments