@@ -205,6 +205,35 @@ def split_json_objects(raw: str) -> list[str]:
205205 return expanded
206206
207207
208+ def _merge_reasoning_details (details : list , chunk : object ) -> None :
209+ """Merge reasoning_details delta items into a list in-place.
210+
211+ Items sharing an integer index are merged: text and summary deltas
212+ concatenate when string-valued, other fields overwrite with the latest
213+ delta. Items without a usable index are appended in arrival order.
214+ """
215+ items = chunk if isinstance (chunk , list ) else ([chunk ] if isinstance (chunk , dict ) else [])
216+ for item in items :
217+ if not isinstance (item , dict ):
218+ continue
219+ idx = item .get ('index' )
220+ existing = None
221+ if isinstance (idx , int ) and idx >= 0 :
222+ existing = next ((e for e in details if e .get ('index' ) == idx ), None )
223+ if existing is None :
224+ new_entry = dict (item )
225+ new_entry .setdefault ('type' , 'reasoning.text' )
226+ details .append (new_entry )
227+ continue
228+ for k , v in item .items ():
229+ if k in ('text' , 'summary' ):
230+ if isinstance (v , str ):
231+ base = existing .get (k )
232+ existing [k ] = (base + v ) if isinstance (base , str ) else v
233+ else :
234+ existing [k ] = v
235+
236+
208237def get_citation_source_from_tool_result (
209238 tool_name : str , tool_params : dict , tool_result : str , tool_id : str = ''
210239) -> list [dict ]:
@@ -509,6 +538,8 @@ def serialize_output(output: list) -> str:
509538 pass
510539
511540 reasoning_content = '' .join (reasoning_parts ).strip ()
541+ if not reasoning_content :
542+ continue # no displayable text; item stays in output for round-trip
512543
513544 duration = item .get ('duration' )
514545 status = item .get ('status' , 'in_progress' )
@@ -3582,15 +3613,43 @@ async def non_streaming_chat_response_handler(response, ctx):
35823613 # otherwise generate from response content
35833614 response_output = response_data .get ('output' )
35843615 if not response_output :
3585- response_output = [
3616+ message_obj = choices [0 ].get ('message' , {})
3617+ reasoning_text = (
3618+ message_obj .get ('reasoning_content' )
3619+ or message_obj .get ('reasoning' )
3620+ )
3621+ reasoning_details = message_obj .get ('reasoning_details' )
3622+
3623+ response_output = []
3624+
3625+ if reasoning_text or reasoning_details :
3626+ r_item = {
3627+ 'type' : 'reasoning' ,
3628+ 'id' : output_id ('r' ),
3629+ 'status' : 'completed' ,
3630+ 'start_tag' : '<think>' ,
3631+ 'end_tag' : '</think>' ,
3632+ 'attributes' : {'type' : 'reasoning_content' },
3633+ 'content' : [{'type' : 'output_text' , 'text' : reasoning_text }] if reasoning_text else [],
3634+ 'summary' : None ,
3635+ }
3636+ if reasoning_details :
3637+ r_item ['reasoning_details' ] = (
3638+ reasoning_details
3639+ if isinstance (reasoning_details , list )
3640+ else [reasoning_details ]
3641+ )
3642+ response_output .append (r_item )
3643+
3644+ response_output .append (
35863645 {
35873646 'type' : 'message' ,
35883647 'id' : output_id ('msg' ),
35893648 'status' : 'completed' ,
35903649 'role' : 'assistant' ,
35913650 'content' : [{'type' : 'output_text' , 'text' : content }],
35923651 }
3593- ]
3652+ )
35943653
35953654 await event_emitter (
35963655 {
@@ -3936,6 +3995,8 @@ def set_last_text(out, text):
39363995
39373996 # Initialize output: use existing from message if continuing, else create new
39383997 existing_output = message .get ('output' ) if message else None
3998+ _pending_reasoning_details = []
3999+
39394000 if existing_output :
39404001 output = existing_output
39414002 else :
@@ -4319,9 +4380,14 @@ async def flush_pending_delta_data(threshold: int = 0):
43194380 or delta .get ('reasoning' )
43204381 or delta .get ('thinking' )
43214382 )
4383+ reasoning_details_chunk = delta .get ('reasoning_details' )
4384+
4385+ # Only create a reasoning item for visible reasoning text.
4386+ # Details-only deltas (e.g. Gemini encrypted blobs) are
4387+ # buffered to avoid splitting the assistant message mid-stream.
43224388 if reasoning_content :
43234389 if not output or output [- 1 ].get ('type' ) != 'reasoning' :
4324- reasoning_item = {
4390+ output . append ( {
43254391 'type' : 'reasoning' ,
43264392 'id' : output_id ('r' ),
43274393 'status' : 'in_progress' ,
@@ -4331,23 +4397,37 @@ async def flush_pending_delta_data(threshold: int = 0):
43314397 'content' : [],
43324398 'summary' : None ,
43334399 'started_at' : time .time (),
4334- }
4335- output .append (reasoning_item )
4336- else :
4337- reasoning_item = output [- 1 ]
4400+ })
43384401
4339- # Append to reasoning content
4402+ if reasoning_content :
4403+ reasoning_item = output [- 1 ]
43404404 parts = reasoning_item .get ('content' , [])
43414405 if parts and parts [- 1 ].get ('type' ) == 'output_text' :
43424406 parts [- 1 ]['text' ] += reasoning_content
43434407 else :
4344- reasoning_item ['content' ] = [
4345- {
4346- 'type' : 'output_text' ,
4347- 'text' : reasoning_content ,
4348- }
4349- ]
4408+ reasoning_item ['content' ] = [{'type' : 'output_text' , 'text' : reasoning_content }]
43504409
4410+ # Flush any buffered details-only chunks into this reasoning item.
4411+ if _pending_reasoning_details :
4412+ _merge_reasoning_details (
4413+ reasoning_item .setdefault ('reasoning_details' , []),
4414+ _pending_reasoning_details ,
4415+ )
4416+ _pending_reasoning_details .clear ()
4417+
4418+ # Accumulate raw structured reasoning_details for provider round-trip.
4419+ if reasoning_details_chunk :
4420+ if output and output [- 1 ].get ('type' ) == 'reasoning' :
4421+ _merge_reasoning_details (
4422+ output [- 1 ].setdefault ('reasoning_details' , []),
4423+ reasoning_details_chunk ,
4424+ )
4425+ else :
4426+ # Buffer until a safe boundary (end-of-stream or real reasoning text).
4427+ items = reasoning_details_chunk if isinstance (reasoning_details_chunk , list ) else [reasoning_details_chunk ]
4428+ _pending_reasoning_details .extend (items )
4429+
4430+ if reasoning_content or reasoning_details_chunk :
43514431 data = {'content' : serialize_output (full_output ())}
43524432
43534433 if value :
@@ -4563,6 +4643,30 @@ async def flush_pending_delta_data(threshold: int = 0):
45634643 )
45644644 reasoning_item ['status' ] = 'completed'
45654645
4646+ # Flush any buffered reasoning_details that never found a reasoning item.
4647+ if _pending_reasoning_details :
4648+ target = next ((item for item in output if item .get ('type' ) == 'reasoning' ), None )
4649+ if target is None :
4650+ target = {
4651+ 'type' : 'reasoning' ,
4652+ 'id' : output_id ('r' ),
4653+ 'status' : 'completed' ,
4654+ 'start_tag' : '<think>' ,
4655+ 'end_tag' : '</think>' ,
4656+ 'attributes' : {'type' : 'reasoning_content' },
4657+ 'content' : [],
4658+ 'summary' : None ,
4659+ 'started_at' : time .time (),
4660+ 'ended_at' : time .time (),
4661+ 'duration' : 0 ,
4662+ }
4663+ output .insert (0 , target )
4664+ _merge_reasoning_details (
4665+ target .setdefault ('reasoning_details' , []),
4666+ _pending_reasoning_details ,
4667+ )
4668+ _pending_reasoning_details .clear ()
4669+
45664670 if response_tool_calls :
45674671 tool_calls .append (_split_tool_calls (response_tool_calls ))
45684672
0 commit comments