@@ -215,6 +215,11 @@ def stream_chunks(
215215 if i > 0 :
216216 num_of_completion_tokens = i + 1
217217
218+ # Skip chunks with empty choices (e.g., Azure OpenAI heartbeat chunks)
219+ if not chunk .choices :
220+ yield chunk
221+ continue
222+
218223 delta = chunk .choices [0 ].delta
219224
220225 if delta .content :
@@ -249,9 +254,14 @@ def stream_chunks(
249254 if collected_output_data :
250255 output_data = "" .join (collected_output_data )
251256 else :
252- collected_function_call ["arguments" ] = json .loads (
253- collected_function_call ["arguments" ]
254- )
257+ if collected_function_call ["arguments" ]:
258+ try :
259+ collected_function_call ["arguments" ] = json .loads (
260+ collected_function_call ["arguments" ]
261+ )
262+ except json .JSONDecodeError :
263+ # Keep as string if not valid JSON
264+ pass
255265 output_data = collected_function_call
256266
257267 processed_messages = extract_chat_completion_messages (kwargs ["messages" ])
@@ -1406,6 +1416,11 @@ def stream_parse_chunks(
14061416 if i > 0 :
14071417 num_of_completion_tokens = i + 1
14081418
1419+ # Skip chunks with empty choices (e.g., Azure OpenAI heartbeat chunks)
1420+ if not chunk .choices :
1421+ yield chunk
1422+ continue
1423+
14091424 delta = chunk .choices [0 ].delta
14101425
14111426 if delta .content :
@@ -1440,9 +1455,14 @@ def stream_parse_chunks(
14401455 if collected_output_data :
14411456 output_data = "" .join (collected_output_data )
14421457 else :
1443- collected_function_call ["arguments" ] = json .loads (
1444- collected_function_call ["arguments" ]
1445- )
1458+ if collected_function_call ["arguments" ]:
1459+ try :
1460+ collected_function_call ["arguments" ] = json .loads (
1461+ collected_function_call ["arguments" ]
1462+ )
1463+ except json .JSONDecodeError :
1464+ # Keep as string if not valid JSON
1465+ pass
14461466 output_data = collected_function_call
14471467
14481468 processed_messages = extract_chat_completion_messages (kwargs ["messages" ])
0 commit comments