@@ -139,22 +139,22 @@ async def stream(
139
139
140
140
logger .debug ("got response from model" )
141
141
yield self .format_chunk ({"chunk_type" : "message_start" })
142
- yield self .format_chunk ({"chunk_type" : "content_start" , "data_type" : "text" })
143
142
144
143
tool_calls : dict [int , list [Any ]] = {}
144
+ started_reasoning = False
145
+ started_text = False
145
146
146
147
async for event in response :
147
148
# Defensive: skip events with empty or missing choices
148
149
if not getattr (event , "choices" , None ):
149
150
continue
150
151
choice = event .choices [0 ]
151
152
152
- if choice .delta .content :
153
- yield self .format_chunk (
154
- {"chunk_type" : "content_delta" , "data_type" : "text" , "data" : choice .delta .content }
155
- )
156
-
157
153
if hasattr (choice .delta , "reasoning_content" ) and choice .delta .reasoning_content :
154
+ if not started_reasoning :
155
+ yield self .format_chunk ({"chunk_type" : "content_start" , "data_type" : "reasoning_content" })
156
+ started_reasoning = True
157
+
158
158
yield self .format_chunk (
159
159
{
160
160
"chunk_type" : "content_delta" ,
@@ -163,14 +163,27 @@ async def stream(
163
163
}
164
164
)
165
165
166
+ if choice .delta .content :
167
+ if started_reasoning :
168
+ yield self .format_chunk ({"chunk_type" : "content_stop" , "data_type" : "reasoning_content" })
169
+ started_reasoning = False
170
+
171
+ if not started_text :
172
+ yield self .format_chunk ({"chunk_type" : "content_start" , "data_type" : "text" })
173
+ started_text = True
174
+
175
+ yield self .format_chunk (
176
+ {"chunk_type" : "content_delta" , "data_type" : "text" , "data" : choice .delta .content }
177
+ )
178
+
166
179
for tool_call in choice .delta .tool_calls or []:
167
180
tool_calls .setdefault (tool_call .index , []).append (tool_call )
168
181
169
182
if choice .finish_reason :
183
+ if started_text :
184
+ yield self .format_chunk ({"chunk_type" : "content_stop" , "data_type" : "text" })
170
185
break
171
186
172
- yield self .format_chunk ({"chunk_type" : "content_stop" , "data_type" : "text" })
173
-
174
187
for tool_deltas in tool_calls .values ():
175
188
yield self .format_chunk ({"chunk_type" : "content_start" , "data_type" : "tool" , "data" : tool_deltas [0 ]})
176
189
0 commit comments