@@ -810,6 +810,7 @@ async def chat_completion_stream_generator(
810
810
tool_messages = []
811
811
812
812
# Calculate base_index once before the loop
813
+ # This represents the number of completed tool calls
813
814
base_index = 0
814
815
for msg in harmony_parser .messages :
815
816
if (msg .channel == "commentary"
@@ -818,6 +819,9 @@ async def chat_completion_stream_generator(
818
819
"functions." )):
819
820
base_index += 1
820
821
822
+ # next_tool_index tracks the index for the next NEW tool call
823
+ next_tool_index = base_index
824
+
821
825
for group in groups :
822
826
group_channel = group ['channel' ]
823
827
group_recipient = group ['recipient' ]
@@ -832,6 +836,7 @@ async def chat_completion_stream_generator(
832
836
and group_recipient .startswith ("functions." )):
833
837
834
838
if prev_recipient != group_recipient :
839
+ # New tool call - emit the opening message
835
840
tool_name = group_recipient .split (
836
841
"functions." , 1 )[1 ]
837
842
tool_messages .append (DeltaToolCall (
@@ -841,15 +846,19 @@ async def chat_completion_stream_generator(
841
846
name = tool_name ,
842
847
arguments = "" ,
843
848
),
844
- index = base_index ,
849
+ index = next_tool_index ,
845
850
))
846
851
prev_recipient = group_recipient
847
- # Increment index for next tool call
848
- base_index += 1
852
+ # Increment for any subsequent new tool calls in this chunk
853
+ next_tool_index += 1
849
854
850
855
if group_text :
856
+ # Stream arguments for the ongoing tool call
857
+ # The current call index is next_tool_index - 1 if we just
858
+ # opened it, OR base_index if continuing from prev chunk
859
+ tool_call_index = next_tool_index - 1 if next_tool_index > base_index else base_index
851
860
tool_messages .append (DeltaToolCall (
852
- index = base_index - 1 , # Use the index of the current tool call
861
+ index = tool_call_index ,
853
862
function = DeltaFunctionCall (
854
863
arguments = group_text ),
855
864
))
0 commit comments