OK, now I need to think about this issue differently.
The issue is about LiteLLM proxy returning tool_calls with finish_reason: "stop" instead of "tool_calls". The code in handleStream already handles this case by checking if there are tool_calls when finish_reason is "stop" and converting the finish_reason to "tool_calls".
But wait - let me re-read the issue one more time:
Host agent reports "no response from subagent" and does not execute the tool call.
The phrase "no response from subagent" is key. This suggests the subagent completed without returning any content to the host agent.
Let me look at the runForwarding function again:
return tools.ResultSuccess(s.GetLastAssistantMessageContent()), nil
This returns the last assistant message content. If the subagent's last message only has tool_calls (no text content), GetLastAssistantMessageContent() returns an empty string.
But actually, when a subagent makes tool_calls, the subagent's loop should:
- Execute the tool_calls
- Send the results back to the model
- Get a response (text or more tool_calls)
- Repeat until the model says stop
So the subagent's last message should have text content (the final response to the user).
Unless... the subagent's loop doesn't process the tool_calls correctly because of the LiteLLM behavior.
Let me think about the flow again:
- Subagent receives a task
- Subagent calls the LLM with the task
- LLM returns tool_calls with finish_reason: "stop" (LiteLLM behavior)
handleStream processes the response
- If there are tool_calls,
finishReason is set to "tool_calls" and Stopped is set to false
- The subagent's loop calls
processToolCalls with the tool_calls
- Tool calls are executed
- Tool results are sent back to the LLM
- LLM returns the final response
- Subagent's loop exits
The issue is at step 3-6. If the LLM returns tool_calls with finish_reason: "stop", the code should:
- Detect the tool_calls from the delta chunks
- Set finish_reason to "tool_calls"
- Set Stopped to false
- Continue to
processToolCalls
But if LiteLLM is NOT sending tool_calls in the delta chunks, then the code won't detect them.
Actually, I think the issue might be different. Let me re-read the issue one more time:
The subagent returns a valid tool call object (type: function, name: company_search, arguments: {...})
finishes with finish_reason: "stop"
So the subagent DOES return a valid tool call. The question is: does the subagent's loop detect and process this tool call?
If the subagent's loop detects the tool call and calls processToolCalls, then the tool call should be executed. If the tool call is executed, the result should be sent back to the LLM, and the subagent should continue iterating.
But the issue says the host agent reports "no response from subagent". This suggests the subagent completed without producing any meaningful output.
Wait, maybe the issue is that the subagent's loop exits immediately after receiving tool_calls (because Stopped is still true even though finish_reason is "tool_calls")?
Let me look at the code again:
return streamResult{
...
Stopped: len(toolCalls) == 0,
...
}, nil
So Stopped is len(toolCalls) == 0. If there are tool_calls, Stopped is false. This should cause the loop to continue.
But wait - let me look at the final path in the loop (when EOF is received):
// If the stream completed without producing any content or tool calls, likely because of a token limit, stop to avoid breaking the request loop
stoppedDueToNoOutput := fullContent.Len() == 0 && len(toolCalls) == 0
...
return streamResult{
...
Stopped: stoppedDueToNoOutput,
...
}, nil
In the final path, Stopped is stoppedDueToNoOutput, which is fullContent.Len() == 0 && len(toolCalls) == 0. So if there are tool_calls, Stopped is false.
Hmm, this all looks correct. The code should correctly handle the case where finish_reason: "stop" but there are tool_calls.
Let me look at the issue from a completely different angle. Maybe the issue is not in the stream parsing but in how the subagent's result is processed by the host.
Actually, I just realized something. The issue says:
Host agent reports "no response from subagent" and does not execute the tool call.
The host agent is the one that should execute the tool call. But why would the host agent need to execute the subagent's tool call?
Actually, I think I've been misunderstanding the issue. Let me re-read it:
When using cagent with a LiteLLM proxy (OpenAI-compatible API), a subagent can return a valid tool_calls response, but the host agent reports "no response from subagent" and does not execute the tool call.
So the issue is:
- Host agent calls subagent (e.g., via
run_skill or transfer_task)
- Subagent receives the task and makes tool_calls
- Subagent returns a response to the host
- Host agent doesn't see the tool_calls and doesn't execute them
But why would the host agent need to execute the subagent's tool calls? The subagent should execute its own tool calls.
Unless the issue is about how the result is propagated. When the subagent completes, the host agent should receive the subagent's final message. But if the subagent's final message has tool_calls (not executed text content), the host agent should see those tool_calls.
Wait, but that doesn't make sense either. If the subagent makes tool_calls, it should execute them before returning to the host. The subagent shouldn't return a response with tool_calls that haven't been executed.
Let me think about this differently. The issue might be:
- Subagent receives a task
- Subagent calls LLM
- LLM returns tool_calls with finish_reason: "stop"
- Subagent's loop sees finish_reason: "stop" and thinks the task is complete
- Subagent returns the tool_calls as the response (not executing them)
- Host agent sees the response and reports "no response" (because the response is just tool_calls, not text)
If this is the case, the issue is that the subagent's loop exits without processing the tool_calls because it thinks finish_reason: "stop" means the task is complete.
But looking at the handleStream code, this should NOT happen. The code checks:
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
...
return streamResult{
...
Stopped: len(toolCalls) == 0,
...
}, nil
If there are tool_calls, finish_reason is set to "tool_calls" and Stopped is false. So the subagent's loop should continue.
Unless the issue is that choice.Delta.ToolCalls is empty when the chunk with finish_reason: "stop" is received. If LiteLLM is NOT sending tool_calls in the delta chunks, then toolCalls will be empty, and the code will return with finish_reason: "stop" and Stopped: true.
So the issue is likely that LiteLLM is NOT sending tool_calls in the delta chunks when finish_reason: "stop".
But wait, the issue says:
The subagent response includes a valid tool call object (type: function, name: company_search, arguments: {...})
So the tool_calls ARE in the response. The question is where they are in the response.
In OpenAI's streaming API, tool_calls are sent in the delta chunks. But if LiteLLM is translating between different APIs, it might be sending the tool_calls in a different format.
Actually, let me look at the LiteLLM source code to understand how it handles tool_calls.
No wait, I shouldn't search the internet. Let me think about this differently.
The issue is specific to LiteLLM proxy. The code works with other providers (e.g., direct OpenAI API). So the issue must be in how the response is parsed, not in the stream processing.
Actually, I think I need to look at the specific provider that handles LiteLLM. LiteLLM is OpenAI-compatible, so it uses the OpenAI provider.
Let me look at the OpenAI provider:
Actually, let me focus on the issue. The problem is:
- Subagent receives tool_calls with finish_reason: "stop" from LiteLLM
- The code in
handleStream should detect the tool_calls and set finish_reason to "tool_calls"
- But the tool_calls are not being detected
The most likely reason is that the tool_calls are not in the delta chunks. If LiteLLM sends the tool_calls in a different format, the code won't detect them.
But actually, looking at the streaming.go code, I see:
if len(choice.Delta.ToolCalls) > 0 {
// Process each tool call delta
for _, delta := range choice.Delta.ToolCalls {
...
}
continue
}
This code processes tool_calls from the delta. If LiteLLM sends tool_calls in the delta, this code should work.
But wait - what if LiteLLM sends tool_calls in the final chunk with finish_reason: "stop" and delta.ToolCalls is empty? In that case, the tool_calls won't be detected.
Actually, in OpenAI's streaming API, tool_calls are ALWAYS in the delta chunks. The final chunk has finish_reason: "tool_calls" (or "stop" in some cases) and an empty delta. So if the final chunk has finish_reason: "stop" and empty delta, the tool_calls should have been accumulated from previous chunks.
But what if LiteLLM is sending the tool_calls in a different way? For example, what if LiteLLM is sending the tool_calls in the final chunk's message field instead of in the delta chunks?
Actually, I just realized something. Let me look at the stream response structure more carefully.
Actually, I think the issue might be simpler. Let me look at the handleStream function again:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
recordUsage()
applyXMLFallback()
finishReason := choice.FinishReason
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
...
Stopped: len(toolCalls) == 0,
FinishReason: finishReason,
...
}, nil
}
This code is in the early return path. If finish_reason == "stop", it returns immediately. At this point, it checks if there are tool_calls accumulated from previous chunks. If there are, it sets finish_reason to "tool_calls".
But the key question is: are there tool_calls accumulated from previous chunks?
In OpenAI's streaming API, the model sends tool_calls in the delta chunks. The tool_calls are accumulated across multiple chunks. The final chunk has finish_reason: "tool_calls".
But if LiteLLM sends finish_reason: "stop" in the final chunk instead of finish_reason: "tool_calls", the code enters the early return path. At this point, the tool_calls should have been accumulated from previous chunks.
So the question is: does LiteLLM send tool_calls in the delta chunks before the final chunk?
If the model (Gemini) sends tool_calls in the delta chunks, and LiteLLM forwards them without modification, then the tool_calls should be accumulated before the final chunk.
But if LiteLLM is somehow filtering or modifying the delta chunks, the tool_calls might not be accumulated.
Actually, I think I need to look at this from a different angle. Let me search for any existing tests or code related to this issue.
Actually, let me re-read the issue one more time:
The subagent returns a valid tool call object (type: function, name: company_search, arguments: {...})
finishes with finish_reason: "stop"
I think the issue is that the tool_calls are in the response, but the finish_reason is "stop" instead of "tool_calls". The question is: are the tool_calls in the delta chunks or somewhere else?
If the tool_calls are in the delta chunks, the code should detect them. If the tool_calls are NOT in the delta chunks, the code won't detect them.
The issue says:
I can reproduce consistently with LiteLLM as the proxy in front of an OpenAI-compatible endpoint.
So the issue is specific to LiteLLM. This suggests that LiteLLM is sending the tool_calls in a different format.
Actually, I just thought of something. In OpenAI's streaming API, when a model returns tool_calls, the streaming response has:
- Multiple chunks with delta.ToolCalls containing tool_call deltas
- A final chunk with delta.ToolCalls empty (or nil) and finish_reason: "tool_calls"
But if the model (Gemini via LiteLLM) returns tool_calls with finish_reason: "stop", the streaming response might have:
- Multiple chunks with delta.ToolCalls containing tool_call deltas
- A final chunk with delta.ToolCalls empty (or nil) and finish_reason: "stop"
In this case, the code should still detect the tool_calls because they were accumulated from previous chunks.
Unless... the final chunk has delta.ToolCalls containing the tool_calls? In that case, the code enters the early return path BEFORE processing the delta.ToolCalls.
Actually, let me look at the streaming.go code again:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
recordUsage()
applyXMLFallback()
finishReason := choice.FinishReason
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
...
Stopped: len(toolCalls) == 0,
...
}, nil
}
This code returns immediately when finish_reason == "stop". It does NOT check choice.Delta.ToolCalls. So if the final chunk has tool_calls in the delta, they won't be detected.
Wait, but in OpenAI's API, the final chunk should have an empty delta. The tool_calls should have been accumulated from previous chunks.
But what if LiteLLM sends the tool_calls in the final chunk's delta? In that case, the tool_calls won't be detected because the code returns immediately when finish_reason == "stop".
Hmm, but actually, the early return path checks len(toolCalls) > 0 and sets finishReason = "tool_calls" if there are tool_calls. But the tool_calls would only be accumulated from previous chunks. If the tool_calls are in the final chunk's delta, they won't be in toolCalls.
So the issue might be that LiteLLM sends the tool_calls in the final chunk's delta, along with finish_reason: "stop". In that case, the code enters the early return path, but toolCalls is empty (because the tool_calls haven't been accumulated yet). The code then returns with finish_reason: "stop" and Stopped: true.
To fix this issue, the code should also check choice.Delta.ToolCalls in the early return path.
Actually, wait. Let me re-read the code:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
recordUsage()
applyXMLFallback()
finishReason := choice.FinishReason
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
...
Stopped: len(toolCalls) == 0,
...
}, nil
}
This code returns when finish_reason == "stop". But before returning, it checks if there are tool_calls. If there are, it sets finish_reason to "tool_calls".
But if the tool_calls are in the final chunk's delta, they won't be detected. The code should check choice.Delta.ToolCalls before returning.
Actually, I think I need to also check len(choice.Delta.ToolCalls) > 0 in the early return path.
Wait, let me re-read the issue one more time. The issue says:
The subagent returns a valid tool call object (type: function, name: company_search, arguments: {...})
finishes with finish_reason: "stop"
If the tool_calls are in the final chunk's delta, the code would need to process them before returning. But the current code returns immediately when finish_reason == "stop".
So the fix would be to also check choice.Delta.ToolCalls in the early return path and process them if present.
Actually, looking at the streaming.go code more carefully:
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return streamResult{Stopped: true}, fmt.Errorf("error receiving from stream: %w", err)
}
if response.Usage != nil {
messageUsage = response.Usage
}
if len(response.Choices) == 0 {
continue
}
choice := response.Choices[0]
if len(choice.Delta.ThoughtSignature) > 0 {
thoughtSignature = choice.Delta.ThoughtSignature
}
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
recordUsage()
applyXMLFallback()
finishReason := choice.FinishReason
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
Calls: toolCalls,
Content: fullContent.String(),
ReasoningContent: fullReasoningContent.String(),
ThinkingSignature: thinkingSignature,
ThoughtSignature: thoughtSignature,
Stopped: len(toolCalls) == 0, // stop only when there are no tool calls to execute
FinishReason: finishReason,
Usage: messageUsage,
}, nil
}
// Track the provider's explicit finish reason (e.g. tool_calls) so we
// can prefer it over inference after the loop. stop/length are already
// handled by the early return above.
if choice.FinishReason != "" {
providerFinishReason = choice.FinishReason
}
// Handle tool calls
if len(choice.Delta.ToolCalls) > 0 {
// Process each tool call delta
for _, delta := range choice.Delta.ToolCalls {
...
}
continue
}
...
}
I see the issue now. When finish_reason == "stop", the code returns immediately. It doesn't check choice.Delta.ToolCalls. So if the final chunk has tool_calls in the delta, they won't be detected.
In OpenAI's streaming API, the final chunk typically has an empty delta. The tool_calls should have been accumulated from previous chunks.
But in LiteLLM's case, it seems like the final chunk might have tool_calls in the delta. In that case, the code should process them before returning.
The fix would be to process choice.Delta.ToolCalls before returning in the early return path.
Let me also check the final path (when EOF is received):
recordUsage()
applyXMLFallback()
// If the stream completed without producing any content or tool calls, likely because of a token limit, stop to avoid breaking the request loop
stoppedDueToNoOutput := fullContent.Len() == 0 && len(toolCalls) == 0
// Prefer the provider's explicit finish reason when available (e.g.
// tool_calls). Only fall back to inference when no explicit reason was
// received (stream ended with bare EOF):
finishReason := providerFinishReason
if finishReason == "" {
switch {
case len(toolCalls) > 0:
finishReason = chat.FinishReasonToolCalls
case fullContent.Len() > 0:
finishReason = chat.FinishReasonStop
default:
finishReason = chat.FinishReasonNull
}
}
// Ensure finish reason agrees with the actual stream output.
switch {
case finishReason == chat.FinishReasonToolCalls && len(toolCalls) == 0:
finishReason = chat.FinishReasonNull
case finishReason == chat.FinishReasonStop && len(toolCalls) > 0:
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
Calls: toolCalls,
Content: fullContent.String(),
ReasoningContent: fullReasoningContent.String(),
ThinkingSignature: thinkingSignature,
ThoughtSignature: thoughtSignature,
Stopped: stoppedDueToNoOutput,
FinishReason: finishReason,
Usage: messageUsage,
}, nil
In the final path, the code also checks len(toolCalls) > 0 and sets finish_reason to "tool_calls" if there are tool_calls. But again, if the tool_calls are in the last chunk's delta and the chunk has finish_reason: "stop", the tool_calls won't be detected because the early return path returns before processing the delta.
So the fix is to process choice.Delta.ToolCalls in the early return path when finish_reason == "stop" and there are tool_calls in the delta.
Let me write the fix:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
recordUsage()
applyXMLFallback()
finishReason := choice.FinishReason
// Process any tool_calls in the final chunk's delta (some proxies like LiteLLM
// may send tool_calls in the final chunk's delta even when finish_reason is "stop")
if len(choice.Delta.ToolCalls) > 0 {
for _, delta := range choice.Delta.ToolCalls {
idx, exists := toolCallIndex[delta.ID]
if !exists {
idx = len(toolCalls)
toolCallIndex[delta.ID] = idx
toolCalls = append(toolCalls, tools.ToolCall{
ID: delta.ID,
Type: delta.Type,
})
}
tc := &toolCalls[idx]
// Track if we're learning the name for the first time
learningName := delta.Function.Name != "" && tc.Function.Name == ""
// Update fields from delta
if delta.Type != "" {
tc.Type = delta.Type
}
if delta.Function.Name != "" {
tc.Function.Name = delta.Function.Name
}
if delta.Function.Arguments != "" {
tc.Function.Arguments += delta.Function.Arguments
}
}
}
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
Calls: toolCalls,
Content: fullContent.String(),
ReasoningContent: fullReasoningContent.String(),
ThinkingSignature: thinkingSignature,
ThoughtSignature: thoughtSignature,
Stopped: len(toolCalls) == 0,
FinishReason: finishReason,
Usage: messageUsage,
}, nil
}
Wait, but this seems like a lot of code duplication. Let me think about a cleaner solution.
Actually, the cleaner solution would be to move the tool_calls processing before the early return check. But that might change the behavior for other providers.
Alternatively, I could add a continue after processing tool_calls in the early return path, so the code doesn't return but continues to the next chunk. But this might cause issues with other providers.
Actually, the cleanest solution would be to add a check for tool_calls in the delta before the early return. If there are tool_calls in the delta, process them and then re-check the finish_reason.
Hmm, but actually, looking at the code more carefully:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
...
return streamResult{...}, nil
}
This returns immediately. If there are tool_calls in the delta, they won't be processed.
The fix should be to process the tool_calls in the delta before returning. Let me think about how to do this cleanly.
One option is to extract the tool_calls processing into a helper function and call it both before the early return and in the main loop. But that might be overkill.
Another option is to just add the tool_calls processing inline before the return.
Actually, looking at the code more carefully, I think the issue is simpler. The applyXMLFallback function is called, which extracts tool_calls from XML blocks. But it only works if there are XML blocks in the content.
applyXMLFallback := func() {
if len(toolCalls) > 0 {
return
}
extracted, textBefore, found := extractXMLToolCalls(fullContent.String())
if !found {
return
}
...
toolCalls = extracted
...
}
This function is called in the early return path. It checks if there are already tool_calls. If there are, it returns early. If there aren't, it tries to extract them from XML blocks.
So the applyXMLFallback function is designed to handle the case where tool_calls are in XML blocks in the content. But it doesn't handle the case where tool_calls are in the delta.
OK, so the issue is clear now. The fix should be to process choice.Delta.ToolCalls in the early return path.
Let me write the fix. I'll add the tool_calls processing inline before the return.
Actually wait, I need to also look at the final path (EOF path) to see if there's a similar issue there.
Looking at the final path:
recordUsage()
applyXMLFallback()
// If the stream completed without producing any content or tool calls, likely because of a token limit, stop to avoid breaking the request loop
stoppedDueToNoOutput := fullContent.Len() == 0 && len(toolCalls) == 0
// Prefer the provider's explicit finish reason when available (e.g.
// tool_calls). Only fall back to inference when no explicit reason was
// received (stream ended with bare EOF):
finishReason := providerFinishReason
if finishReason == "" {
switch {
case len(toolCalls) > 0:
finishReason = chat.FinishReasonToolCalls
...
}
}
// Ensure finish reason agrees with the actual stream output.
switch {
case finishReason == chat.FinishReasonToolCalls && len(toolCalls) == 0:
finishReason = chat.FinishReasonNull
case finishReason == chat.FinishReasonStop && len(toolCalls) > 0:
finishReason = chat.FinishReasonToolCalls
}
In the final path, providerFinishReason is set to the last non-empty finish_reason received. If the last chunk has finish_reason: "stop" but has tool_calls in the delta, providerFinishReason will be "stop", but the tool_calls won't be accumulated because they weren't processed.
Wait, but in the final path, the loop ends via EOF, which means the last chunk was already processed in the loop body. If the last chunk had finish_reason: "stop" and tool_calls in the delta, the code would have entered the early return path and returned. So the final path is only reached if the loop ends via EOF without hitting the early return.
So the issue is only in the early return path. When finish_reason == "stop", the code returns immediately without processing the delta.
OK, I think I have a clear understanding of the issue now. The fix is to process choice.Delta.ToolCalls in the early return path.
Actually, wait. Let me re-read the issue one more time to make sure I understand it correctly:
The subagent returns a valid tool call object (type: function, name: company_search, arguments: {...})
This suggests the tool_calls ARE in the response. But are they in the delta chunks or somewhere else?
If the tool_calls are in previous delta chunks (before the final chunk), they should be accumulated in toolCalls. The early return path should detect them.
But if the tool_calls are only in the final chunk's delta, they won't be accumulated.
The issue says:
finishes with finish_reason: "stop"
This suggests the final chunk has finish_reason: "stop". If the tool_calls are in the final chunk's delta, they won't be detected.
So the fix is to process choice.Delta.ToolCalls in the early return path.
Let me now look at the code more carefully and write the fix.
Actually, I just realized something. The code in the early return path has this comment:
// stop only when there are no tool calls to execute
And it sets Stopped: len(toolCalls) == 0. So if there are tool_calls, Stopped is false.
But if the tool_calls are in the delta and haven't been processed yet, toolCalls will be empty, and Stopped will be true.
So the issue is that the tool_calls in the delta are not being processed, and Stopped is set to true even though there are tool_calls to execute.
OK, I'm confident now. The fix is to process choice.Delta.ToolCalls in the early return path.
Let me write the fix:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
recordUsage()
applyXMLFallback()
// Process any tool_calls in the final chunk's delta. Some proxies like LiteLLM
// may send tool_calls in the final chunk's delta even when finish_reason is "stop".
if len(choice.Delta.ToolCalls) > 0 {
for _, delta := range choice.Delta.ToolCalls {
idx, exists := toolCallIndex[delta.ID]
if !exists {
idx = len(toolCalls)
toolCallIndex[delta.ID] = idx
toolCalls = append(toolCalls, tools.ToolCall{
ID: delta.ID,
Type: delta.Type,
})
}
tc := &toolCalls[idx]
if delta.Type != "" {
tc.Type = delta.Type
}
if delta.Function.Name != "" {
tc.Function.Name = delta.Function.Name
}
if delta.Function.Arguments != "" {
tc.Function.Arguments += delta.Function.Arguments
}
}
}
finishReason := choice.FinishReason
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
Calls: toolCalls,
Content: fullContent.String(),
ReasoningContent: fullReasoningContent.String(),
ThinkingSignature: thinkingSignature,
ThoughtSignature: thoughtSignature,
Stopped: len(toolCalls) == 0,
FinishReason: finishReason,
Usage: messageUsage,
}, nil
}
This fix processes choice.Delta.ToolCalls in the early return path, ensuring that tool_calls in the final chunk's delta are detected.
But wait, I need to also consider the PartialToolCall event emission. Looking at the main loop:
if tc.Function.Name != "" && (learningName || delta.Function.Arguments != "") {
if !emittedPartial[delta.ID] || delta.Function.Arguments != "" {
partial := tools.ToolCall{
ID: tc.ID,
Type: tc.Type,
Function: tools.FunctionCall{
Name: tc.Function.Name,
Arguments: delta.Function.Arguments,
},
}
toolDef := tools.Tool{}
if !emittedPartial[delta.ID] {
toolDef = toolDefMap[tc.Function.Name]
}
events.Emit(PartialToolCall(partial, toolDef, a.Name()))
emittedPartial[delta.ID] = true
}
}
This code emits PartialToolCall events for tool_calls. In the early return path, we might also want to emit these events for tool_calls in the final chunk's delta.
Actually, let me think about this. In the main loop, PartialToolCall events are emitted as tool_calls come in. In the early return path, the tool_calls have already been accumulated from previous chunks, and events have already been emitted for them. So we don't need to emit additional events.
But in the early return path, if there are tool_calls in the final chunk's delta, we might want to emit events for them as well.
Actually, looking at the code more carefully, I see that emittedPartial is used to track which tool_calls have had events emitted. If a tool_call was already partially emitted (from a previous chunk), we don't need to emit another event for the delta.
So in the early return path, we should:
- Process the tool_calls in the delta (accumulate them)
- Emit events for tool_calls that haven't been emitted yet
But this might be overcomplicating things. Let me focus on the core fix: processing the tool_calls in the delta.
Actually, I think the core fix is sufficient. The tool_calls will be accumulated, and the runTurn loop will call processToolCalls with the tool_calls. The events will be emitted by processToolCalls.
OK, let me finalize the fix and write it.
Wait, actually I need to re-examine the code more carefully. Let me trace through the issue step by step.
When the subagent's LLM returns tool_calls with finish_reason: "stop":
- The provider (OpenAI via LiteLLM) sends streaming chunks
- The chunks contain tool_calls in the delta
- The final chunk has
finish_reason: "stop" and possibly tool_calls in the delta
handleStream receives the chunks
- For each chunk,
handleStream processes the delta
- If
finish_reason == "stop", handleStream enters the early return path and returns
- If the tool_calls are in previous chunks, they are accumulated in
toolCalls
- If the tool_calls are in the final chunk's delta, they are NOT processed because the code returns before the delta processing
So the issue is that the tool_calls in the final chunk's delta are not processed.
Actually, wait. Let me re-read the code:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
recordUsage()
applyXMLFallback()
finishReason := choice.FinishReason
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
...
Stopped: len(toolCalls) == 0,
...
}, nil
}
This code is BEFORE the delta processing code:
// Handle tool calls
if len(choice.Delta.ToolCalls) > 0 {
// Process each tool call delta
for _, delta := range choice.Delta.ToolCalls {
...
}
continue
}
So if finish_reason == "stop", the code returns BEFORE processing the delta. The tool_calls in the delta are not processed.
This confirms my understanding. The fix is to process the tool_calls in the delta before returning.
OK, let me write the fix now.
Actually, I realize there's another potential issue. In the early return path, the code checks:
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
This converts finish_reason to "tool_calls" if there are tool_calls. But this only checks len(toolCalls) > 0, which is the accumulated tool_calls from previous chunks. If the tool_calls are in the final chunk's delta, len(toolCalls) will be 0 (or less than the actual number of tool_calls), and the finish_reason won't be converted.
So the fix is to process the tool_calls in the delta before checking len(toolCalls) > 0.
OK, I'm confident now. The fix is:
- Process
choice.Delta.ToolCalls in the early return path
- Then check
len(toolCalls) > 0 and set finish_reason accordingly
Let me write the fix:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
recordUsage()
applyXMLFallback()
// Process any tool_calls in the final chunk's delta. Some proxies like LiteLLM
// may send tool_calls in the final chunk's delta even when finish_reason is "stop",
// which would cause the tool_calls to be missed if not processed here.
if len(choice.Delta.ToolCalls) > 0 {
for _, delta := range choice.Delta.ToolCalls {
idx, exists := toolCallIndex[delta.ID]
if !exists {
idx = len(toolCalls)
toolCallIndex[delta.ID] = idx
toolCalls = append(toolCalls, tools.ToolCall{
ID: delta.ID,
Type: delta.Type,
})
}
tc := &toolCalls[idx]
if delta.Type != "" {
tc.Type = delta.Type
}
if delta.Function.Name != "" {
tc.Function.Name = delta.Function.Name
}
if delta.Function.Arguments != "" {
tc.Function.Arguments += delta.Function.Arguments
}
}
}
finishReason := choice.FinishReason
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
Calls: toolCalls,
Content: fullContent.String(),
ReasoningContent: fullReasoningContent.String(),
ThinkingSignature: thinkingSignature,
ThoughtSignature: thoughtSignature,
Stopped: len(toolCalls) == 0,
FinishReason: finishReason,
Usage: messageUsage,
}, nil
}
This fix processes choice.Delta.ToolCalls in the early return path, ensuring that tool_calls in the final chunk's delta are detected and the finish_reason is correctly set to "tool_calls" if there are tool_calls.
But wait, I need to think about edge cases:
- What if the tool_calls are partial (e.g., only the ID and type are in the delta, not the name)?
- What if the tool_calls have already been accumulated from previous chunks?
For case 1, the code handles partial tool_calls by accumulating them across chunks. The toolCallIndex maps the tool_call ID to the index in the toolCalls slice. If the same tool_call appears in multiple chunks, the code updates the existing entry.
For case 2, the code checks exists in toolCallIndex and only creates a new entry if the tool_call doesn't already exist. If it does exist, the code updates the existing entry.
So the code handles both cases correctly.
Now, let me also think about the emittedPartial tracking. In the main loop, PartialToolCall events are emitted for tool_calls. If the tool_calls are in the final chunk's delta, we might want to emit events for them as well.
But actually, looking at the main loop more carefully:
// Emit PartialToolCall once we have a name, and on subsequent argument deltas.
if tc.Function.Name != "" && (learningName || delta.Function.Arguments != "") {
if !emittedPartial[delta.ID] || delta.Function.Arguments != "" {
...
events.Emit(PartialToolCall(partial, toolDef, a.Name()))
emittedPartial[delta.ID] = true
}
}
This code emits events only if we have a name (not just ID). So for partial tool_calls (only ID and type), no events are emitted until we have a name.
In the early return path, if the tool_calls in the final chunk's delta have a name, we might want to emit events for them. But if the tool_calls are already in toolCalls (from previous chunks), events have already been emitted for them.
So in the early return path, we only need to emit events for new tool_calls that haven't been emitted yet.
Let me update the fix to handle this:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
recordUsage()
applyXMLFallback()
// Process any tool_calls in the final chunk's delta. Some proxies like LiteLLM
// may send tool_calls in the final chunk's delta even when finish_reason is "stop",
// which would cause the tool_calls to be missed if not processed here.
if len(choice.Delta.ToolCalls) > 0 {
for _, delta := range choice.Delta.ToolCalls {
idx, exists := toolCallIndex[delta.ID]
if !exists {
idx = len(toolCalls)
toolCallIndex[delta.ID] = idx
toolCalls = append(toolCalls, tools.ToolCall{
ID: delta.ID,
Type: delta.Type,
})
}
tc := &toolCalls[idx]
learningName := delta.Function.Name != "" && tc.Function.Name == ""
if delta.Type != "" {
tc.Type = delta.Type
}
if delta.Function.Name != "" {
tc.Function.Name = delta.Function.Name
}
if delta.Function.Arguments != "" {
tc.Function.Arguments += delta.Function.Arguments
}
// Emit PartialToolCall for new tool_calls that we just learned the name for
if tc.Function.Name != "" && learningName {
partial := tools.ToolCall{
ID: tc.ID,
Type: tc.Type,
Function: tools.FunctionCall{
Name: tc.Function.Name,
Arguments: "",
},
}
toolDef := toolDefMap[tc.Function.Name]
events.Emit(PartialToolCall(partial, toolDef, a.Name()))
emittedPartial[delta.ID] = true
}
}
}
finishReason := choice.FinishReason
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
Calls: toolCalls,
Content: fullContent.String(),
ReasoningContent: fullReasoningContent.String(),
ThinkingSignature: thinkingSignature,
ThoughtSignature: thoughtSignature,
Stopped: len(toolCalls) == 0,
FinishReason: finishReason,
Usage: messageUsage,
}, nil
}
Hmm, this is getting complicated. Let me simplify the fix.
Actually, I think the core issue is simpler than I thought. The main loop processes tool_calls from the delta and accumulates them. When the final chunk has finish_reason: "stop", the early return path is triggered. At this point, toolCalls should contain all the tool_calls from previous chunks.
But if the final chunk ALSO has tool_calls in the delta, they won't be processed because the early return path returns before the delta processing.
So the fix is to process the delta tool_calls before returning. The fix should be minimal and only add the delta processing to the early return path.
Let me write a cleaner fix:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
recordUsage()
applyXMLFallback()
// Process any remaining tool_calls in the final chunk's delta.
// Some providers (e.g., LiteLLM proxying Gemini) may send tool_calls in the
// final chunk's delta even when finish_reason is "stop". Without this
// processing, such tool_calls would be silently dropped.
if len(choice.Delta.ToolCalls) > 0 {
for _, delta := range choice.Delta.ToolCalls {
idx, exists := toolCallIndex[delta.ID]
if !exists {
idx = len(toolCalls)
toolCallIndex[delta.ID] = idx
toolCalls = append(toolCalls, tools.ToolCall{
ID: delta.ID,
Type: delta.Type,
})
}
tc := &toolCalls[idx]
if delta.Type != "" {
tc.Type = delta.Type
}
if delta.Function.Name != "" {
tc.Function.Name = delta.Function.Name
}
if delta.Function.Arguments != "" {
tc.Function.Arguments += delta.Function.Arguments
}
}
}
finishReason := choice.FinishReason
if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
finishReason = chat.FinishReasonToolCalls
}
return streamResult{
Calls: toolCalls,
Content: fullContent.String(),
ReasoningContent: fullReasoningContent.String(),
ThinkingSignature: thinkingSignature,
ThoughtSignature: thoughtSignature,
Stopped: len(toolCalls) == 0,
FinishReason: finishReason,
Usage: messageUsage,
}, nil
}
This fix is minimal and only adds the delta processing to the early return path. It doesn't change the event emission logic.
OK, let me now implement this fix.
Wait, I also need to think about whether the fix is correct. Let me trace through the scenario:
- Model returns tool_calls with finish_reason: "stop" (via LiteLLM)
- Streaming chunks are received:
- Chunk 1: delta.ToolCalls = [{id: "call_1", type: "function", function: {name: "company_search"}}]
- Chunk 2: delta.ToolCalls = [{id: "call_1", function: {arguments: '{"query": "LiteLLM"}'}}]
- Chunk 3 (final): finish_reason: "stop", delta.ToolCalls = []
handleStream processes the chunks:
- Chunk 1: accumulates tool_calls
- Chunk 2: accumulates tool_calls
- Chunk 3: early return path is triggered,
toolCalls contains the tool_calls from chunks 1 and 2
- The fix processes delta.ToolCalls (which is empty in this case)
- The fix checks
len(toolCalls) > 0 and sets finish_reason to "tool_calls"
This looks correct. The tool_calls are accumulated from previous chunks, and the fix correctly sets finish_reason to "tool_calls".
But wait, the issue says the tool_calls are in the response. If the tool_calls are in the delta chunks, they should be accumulated. If the tool_calls are only in the final chunk's delta, they won't be accumulated.
Let me re-read the issue one more time:
The subagent returns a valid tool call object (type: function, name: company_search, arguments: {...})
I think the tool_calls ARE in the response. The question is whether they're in the delta chunks or the final chunk's delta.
If the tool_calls are in previous delta chunks, they should be accumulated. The early return path should detect them.
But if the tool_calls are only in the final chunk's delta, they won't be accumulated.
Actually, I think the issue might be that LiteLLM sends the tool_calls in a different format. For example, LiteLLM might send the tool_calls as a single chunk at the end (with finish_reason: "stop"). In that case, the tool_calls are in the final chunk's delta, and they won't be processed.
OK, I'm going with the fix I described. It processes choice.Delta.ToolCalls in the early return path, ensuring that tool_calls in the final chunk's delta are detected.
Actually, wait. I just realized something. Let me re-read the code:
if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
...
return streamResult{
...
Stopped: len(toolCalls) == 0,
...
}, nil
}
The code returns immediately when finish_reason == "stop". But what if the final chunk has finish_reason: "stop" AND tool_calls in the delta? In that case:
- The code enters the early return path
toolCalls might be empty (if no tool_calls in previous chunks)
- The code returns with
Stopped: true
So the tool_calls in the final chunk's delta are NOT processed.
This confirms my understanding. The fix is to process choice.Delta.ToolCalls in the early return path.
OK, let me implement the fix now.
Actually, I also want to consider whether the fix might break other scenarios. For example, what if a provider sends tool_calls in the final chunk's delta when finish_reason: "stop" is NOT the case (i.e., finish_reason: "tool_calls")? In that case, the code would enter the early return path and process the delta. But this shouldn't cause any issues because the tool_calls would be accumulated correctly.
Actually wait, if finish_reason: "tool_calls", the code would NOT enter the early return path (because the condition is choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength). So the fix would only affect the finish_reason: "stop" case.
OK, I'm confident the fix is correct and won't break other scenarios. Let me implement it now.
Actually, I also want to make sure the fix handles the case where the tool_calls have already been accumulated from previous chunks. In that case, the fix should NOT create duplicate entries.
Looking at the fix:
idx, exists := toolCallIndex[delta.ID]
if !exists {
idx = len(toolCalls)
toolCallIndex[delta.ID] = idx
toolCalls = append(toolCalls, tools.ToolCall{
ID: delta.ID,
Type: delta.Type,
})
}
This code checks exists in toolCallIndex. If the tool_call already exists, it updates the existing entry. If it doesn't exist, it creates a new entry. So the fix handles the case where tool_calls have already been accumulated correctly.
OK, I'm confident the fix is correct. Let me implement it now.
Actually, I want to also consider the case where the tool_calls in the final chunk's delta are the same as the tool_calls accumulated from previous chunks. In that case, the fix should NOT create duplicate entries.
But wait, the tool_calls in the final chunk's delta are typically empty (or have minimal data). The tool_calls accumulated from previous chunks should have the full data. So the fix should correctly update the existing entries with any new data from the final chunk.
OK, I'm confident the fix is correct. Let me implement it now.
Wait, I should also verify that I understand the issue correctly by looking at any existing tests.
Actually, let me first run the existing tests to make sure I understand the codebase correctly.
Let me look for tests related to handleStream:
<tool_call>
<function=bash_terminal>
<parameter=command>
ls -la /docker-agent/pkg/runtime/test.go
</tool_call>