Skip to content
TheChatArchiveThe Chat Archive
xiaomi/mimo-v2.5-pro· unknownHugging Face ibragim-bad/swe_rebench_07_2026_trajectories

ISSUE DESCRIPTION Subagent toolcalls not handled when using LiteLLM proxy Summary When…

  1. User

    ISSUE DESCRIPTION

    Subagent tool_calls not handled when using LiteLLM proxy

    Summary

    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.

    Environment

    • cagent: v1.19.7
    • OS: Linux (WSL2) x86_64
    • LLM: gemini-pro via LiteLLM proxy (OpenAI-compatible)

    Expected

    Host agent receives the subagent response and executes the tool call(s), then continues the conversation with the tool result.

    Actual

    Host agent reports there is “no response from subagent” even though the subagent response contains a valid tool_calls entry. The requested tool call is not executed.

    Minimal reproduction

    1. Configure cagent to use LiteLLM as the model provider (OpenAI-compatible API).
    2. Run a workflow where the subagent is asked to use tools.
    3. The subagent returns a tool call (e.g., company_search with JSON arguments) and finishes with finish_reason: "stop".
    4. The host agent logs “no response from subagent” and does not invoke the tool.

    Notes

    • The subagent response includes a valid tool call object (type: function, name: company_search, arguments: {"datasources": ["confluence", "github", "gdrive"], "query": "LiteLLM usage teams integrations standards"}).
    • I can reproduce consistently with LiteLLM as the proxy in front of an OpenAI-compatible endpoint.

    Please let me know if you want a sanitized example payload or a minimal agent config.

    ADDITIONAL ADVICE

    Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use git checkout <file> to restore the file to its original state. You can also reset all changes in the repository using git reset --hard command. Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands. However you don't need to use git add or git commit before submitting your changes. In fact, submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.

    CHECKLIST

    Before submitting your solution, please go over the following checklist and make sure you've done everything:

    • If an error was reported in the issue description, I have successfully reproduced it.
    • If an error was reported in the issue description, I have confirmed that my fix resolves the error.
    • I have thought about edge cases and made sure my fix handles them as well.
    • I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.

    Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!

    (Current directory: /docker-agent, current file: none) bash-$

  2. Assistant

    I'll start by exploring the repository structure to understand the codebase and locate relevant files related to subagent tool calls and LiteLLM proxy handling.

  3. Assistant

    Let me get a better view of the repository structure.

  4. Assistant

    This is a Go project. Let me look for files related to subagent tool_calls and LiteLLM proxy handling.

  5. Assistant

    The string "no response from subagent" isn't directly in the source code. Let me search more broadly.

  6. Assistant

    Let me examine the key files related to subagent handling.

  7. Assistant

    Let me search for where the issue might be - tool calls handling and response processing:

  8. Assistant

    Let me look at the model provider and chat files to understand the response handling:

  9. Assistant

    Let me look at the chat package which likely handles tool call processing:

  10. Assistant

    Let me continue reading the chat.go file to see the rest of the file.

  11. Assistant

    Let me search for related terms:

  12. Assistant

    Let me search for how tool calls are processed in the response stream:

  13. Assistant

    Now I need to understand the issue better. The problem is about subagent tool_calls not being handled when using LiteLLM proxy. Let me search for the event stream adapter that handles the Chat Completions API (not the Responses API), since LiteLLM proxy typically uses the Chat Completions API.

  14. Assistant

    Let me look at the runtime handling of tool calls to understand where the issue might be.

  15. Assistant

    Let me look at the runtime loop to understand how tool calls are processed.

  16. Assistant

    Let me look at more of the loop.go file, particularly around the streaming and tool call handling.

  17. Assistant

    Let me look at the part of the file where tool calls are processed and the loop iteration.

  18. Assistant

    Let me look for the streamResult type definition and how tool calls are collected from the stream:

  19. Assistant

    Let me search for streamResult in the whole codebase.

  20. Assistant

    Let me look at the streaming.go file to understand how tool calls are collected from the stream.

  21. Assistant

    Let me read the main loop where tool calls are executed:

  22. Assistant

    Now let me look at GetLastAssistantMessageContent which is what runForwarding uses to get the subagent result:

  23. Assistant

    Let me look at the GetLastAssistantMessageContent implementation:

  24. Assistant

    Let me look at getLastMessageContentByRole:

  25. Assistant

    Let me look at the implementation of getLastMessageContentByRole:

  26. Assistant

    Now I see a potential issue! GetLastAssistantMessageContent() only returns the text content, not tool calls. When a subagent returns only tool calls (with no text content), the function returns an empty string. Let me check what happens with empty results:

  27. Assistant

    Let me check the OpenAI adapter to understand how streaming responses are handled:

  28. Assistant

    Let me look at the oaistream package:

  29. Assistant

    Let me read the adapter.go file in oaistream package to understand how streaming responses are processed:

  30. Assistant

    Now I'm getting closer to the issue! Let me look at the key part of the issue:

    The issue says:

    • "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."
    • The subagent response includes a valid tool call object (type: function, name: company_search, arguments: {...}).

    Looking at the code, I see:

    1. In agent_delegation.go:runForwarding, after the subagent finishes, it returns:
    return tools.ResultSuccess(s.GetLastAssistantMessageContent()), nil
    
    1. GetLastAssistantMessageContent() returns the content of the last assistant message.

    2. In loop.go:recordAssistantMessage, we have:

    if strings.TrimSpace(res.Content) == "" && len(res.Calls) == 0 {
        slog.Debug("Skipping empty assistant message (no content and no tool calls)", "agent", a.Name())
        return nil
    }
    

    This means that if the subagent response has ONLY tool calls and NO text content, the assistant message is NOT added to the session!

    Then when runForwarding calls s.GetLastAssistantMessageContent(), it finds no assistant message (because it was skipped), returns an empty string, and the tool result becomes:

    return tools.ResultSuccess(""), nil
    

    Which is interpreted as an empty result. This is the "no response from subagent" behavior!

    Let me verify this by looking at how the tool result is processed:

    Let me check how the tool result is processed in the host agent's loop:

  31. Assistant

    Let me search for the processToolCalls function.

  32. Assistant

    Let me look at the tool_dispatch.go file:

  33. Assistant

    Now let me search for the "no response from subagent" message more broadly:

  34. Assistant

    Hmm, "no response from subagent" is not found in the code. The issue might be reporting a user-visible message that's not directly in the source code. Let me look at what runForwarding returns and how the caller uses it. The key is that runForwarding returns tools.ResultSuccess(s.GetLastAssistantMessageContent()) which returns the last assistant message's content text only.

    If the subagent's last message had tool_calls but no text content, GetLastAssistantMessageContent() would return empty string. This would result in the tool result being empty, which the host agent might interpret as "no response".

    But wait, let me re-read the issue more carefully. The issue says:

    1. Host agent delegates a task to a subagent
    2. Subagent returns a response with tool_calls
    3. Host agent reports "no response from subagent"

    The issue is that when using LiteLLM proxy (OpenAI-compatible), the subagent gets a response with tool_calls, but the host agent doesn't see those tool calls being executed.

    Let me think about the flow:

    1. Host agent delegates to subagent via runForwarding or runCollecting
    2. Subagent runs its own loop, which involves getting a response from the LLM
    3. If the LLM returns tool_calls, the subagent should execute them
    4. After the subagent finishes, the host agent gets the result

    The issue might be in how the subagent's response is being handled. Let me look at how the subagent's stream is processed in runForwarding:

    childEvents := r.RunStream(ctx, s)
    for event := range childEvents {
        evts.Emit(event)
        if errEvent, ok := event.(*ErrorEvent); ok {
            ...
     return nil, err
        }
    }
    

    And then:

    return tools.ResultSuccess(s.GetLastAssistantMessageContent()), nil
    

    So if the subagent's last message has only tool_calls and no text content, this would return empty.

    But the real issue might be different. Let me think about this more carefully.

    Looking at the streaming.go code, when LiteLLM returns a response with tool_calls, the handleStream function should correctly process them. The key is the condition:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
    

    If LiteLLM returns finish_reason: "stop" with tool calls, this code checks:

    if finishReason == chat.FinishReasonStop && len(toolCalls) > 0 {
        finishReason = chat.FinishReasonToolCalls
    }
    return streamResult{
        Calls:             toolCalls,
        ...
        Stopped:           len(toolCalls) == 0,
        FinishReason:      finishReason,
    }, nil
    

    So Stopped would be false because there are tool calls, and the runtime loop should continue executing them.

    Actually wait, I need to re-read the issue more carefully. Let me look at the "Notes" section:

    The subagent response includes a valid tool call object (type: function, name: company_search, arguments: {...}). I can reproduce consistently with LiteLLM as the proxy in front of an OpenAI-compatible endpoint.

    So the subagent IS getting a response with tool_calls. But the host agent is reporting "no response from subagent".

    Let me think about this differently. Maybe the issue is not about the subagent executing its own tool calls, but about the host agent receiving the subagent's response.

    Actually, I think the issue might be in how the runCollecting function handles the subagent's events. Let me look at it again:

    func (r *LocalRuntime) runCollecting(ctx context.Context, parent *session.Session, cfg SubSessionConfig, onContent func(string)) *agenttool.RunResult {
        ...
        var errMsg string
        events := r.RunStream(ctx, s)
        for event := range events {
            if ctx.Err() != nil {
                break
            }
            if choice, ok := event.(*AgentChoiceEvent); ok && choice.Content != "" {
                if onContent != nil {
                    onContent(choice.Content)
                }
            }
            if errEvt, ok := event.(*ErrorEvent); ok {
                errMsg = errEvt.Error
                break
            }
        }
        ...
        if errMsg != "" {
            return &agenttool.RunResult{ErrMsg: errMsg}
        }
    
        result := s.GetLastAssistantMessageContent()
        parent.AddSubSession(s)
    
        return &agenttool.RunResult{Result: result}
    }
    

    This is the non-interactive path (background agents). The interactive path is runForwarding:

    func (r *LocalRuntime) runForwarding(ctx context.Context, parent *session.Session, evts EventSink, req delegationRequest) (*tools.ToolCallResult, error) {
        ...
        childEvents := r.RunStream(ctx, s)
        for event := range childEvents {
            evts.Emit(event)
            if errEvent, ok := event.(*ErrorEvent); ok {
                ...
                return nil, err
            }
        }
        ...
        return tools.ResultSuccess(s.GetLastAssistantMessageContent()), nil
    }
    

    Both paths use s.GetLastAssistantMessageContent() to get the result. If the subagent's last message has only tool_calls and no text content, this returns empty.

    But wait, the issue says the host agent reports "no response from subagent". This suggests the host agent is checking if the response is empty and reporting this message. Let me search for where this message might be generated.

    Actually, the message "no response from subagent" might not be in the code. It might be a user-facing message generated by the host agent's logic. Let me think about what happens when runForwarding returns an empty result:

    1. runForwarding returns tools.ResultSuccess("") (empty string)
    2. This is returned to handleTaskTransfer
    3. handleTaskTransfer returns this as the tool call result
    4. The tool call result is processed by the runtime loop

    Let me look at how the tool call result is processed. In tool_dispatch.go, the processToolCalls function calls d.Process which handles the tool call execution.

    Actually, I think I need to look at the issue from a different angle. Let me re-read the issue:

    Host agent reports there is "no response from subagent" even though the subagent response contains a valid tool_calls entry. The requested tool call is not executed.

    So the host agent is NOT executing the tool call. This suggests the issue is in how the subagent's response is being processed.

    Wait, I think I misunderstood the issue. Let me re-read it:

    1. The host agent delegates a task to a subagent
    2. The subagent calls the LLM and gets a response with tool_calls
    3. The subagent should execute those tool_calls and continue
    4. But the host agent reports "no response from subagent"

    This suggests the subagent is not executing its tool calls. The issue is that when the subagent gets a response with tool_calls, something is preventing them from being executed.

    Let me look at how the streaming adapter handles tool calls with LiteLLM proxy.

    Actually, I think the issue might be in how LiteLLM sends the tool calls. Let me look at the OpenAI streaming adapter more carefully.

    Looking at oaistream/adapter.go:

    // Convert tool calls if present
    if len(choice.Delta.ToolCalls) > 0 {
        response.Choices[i].Delta.ToolCalls = make([]tools.ToolCall, len(choice.Delta.ToolCalls))
        for j, toolCall := range choice.Delta.ToolCalls {
            id := toolCall.ID
            index := int(toolCall.Index)
            if existing, ok := a.toolCalls[index]; ok && id == "" {
                id = existing
            } else if id != "" {
                a.toolCalls[index] = id
            }
    
            response.Choices[i].Delta.ToolCalls[j] = tools.ToolCall{
                ID:   id,
                Type: tools.ToolType(toolCall.Type),
                Function: tools.FunctionCall{
                    Name:      toolCall.Function.Name,
                    Arguments: toolCall.Function.Arguments,
                },
            }
        }
    }
    

    This looks correct. But wait, what if LiteLLM is not sending the tool calls in the streaming chunks? What if it's sending them differently?

    Actually, let me look at how the handleStream function processes the finish reason. The key issue might be that LiteLLM sends finish_reason: "stop" even when there are tool calls, and the handleStream function might not be correctly detecting this.

    Looking at streaming.go:

    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,
            ...
            Stopped:           len(toolCalls) == 0,
            FinishReason:      finishReason,
        }, nil
    }
    

    So if LiteLLM sends finish_reason: "stop" with tool calls, this should correctly set Stopped: false and FinishReason: "tool_calls". The runtime loop should then execute the tool calls.

    But wait, there's another issue. What if the finish reason is sent BEFORE the tool calls are fully accumulated? Let me look at how streaming chunks are processed.

    Actually, I think I need to look at the issue from a different perspective. The issue says:

    The subagent response includes a valid tool call object (type: function, name: company_search, arguments: {...}).

    This suggests the subagent IS getting a complete tool call in its response. But the host agent is not seeing it.

    Let me think about the flow again:

    1. Host agent calls handleTaskTransfer which calls runForwarding
    2. runForwarding calls r.RunStream(ctx, s) to run the subagent
    3. The subagent runs its own loop, which involves: a. Getting tools b. Sending messages to the LLM c. Processing the LLM's response d. If the response has tool calls, executing them e. Looping back to step b

    The issue might be in step c or d. Let me look at how the subagent's loop processes the LLM's response.

    Looking at loop.go, the main loop calls handleStream to process the streaming response. If the response has tool calls, it calls processToolCalls to execute them.

    But wait, I think I see the issue now. Let me look at the streaming.go code again:

    for {
        response, err := stream.Recv()
        if errors.Is(err, io.EOF) {
            break
        }
        ...
    }
    

    After the loop ends (either by reaching EOF or by returning early), the code returns a streamResult. But what if the stream ends BEFORE the tool calls are fully accumulated?

    Actually, I think the issue might be in how LiteLLM sends the streaming response. Let me think about this differently.

    The issue says the subagent returns a valid tool call with finish_reason: "stop". This suggests the LLM is returning a response with:

    • A tool call in the delta
    • finish_reason: "stop"

    But the streaming adapter might not be correctly handling this case. Let me look at the OpenAI streaming adapter again.

    Actually, I think I need to look at the issue from a completely different angle. Let me re-read the issue one more time:

    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 host agent is reporting "no response from subagent". This is a specific error message. Let me search for where this message might be generated.

    Actually, the message "no response from subagent" might not be in the code. It might be a user-facing message generated by the host agent's logic. Let me think about what happens when runForwarding returns an empty result.

    Wait, I think I see the issue now! Let me look at the runForwarding function again:

    return tools.ResultSuccess(s.GetLastAssistantMessageContent()), nil
    

    This returns the last assistant message's TEXT content. But if the subagent's last message has only tool calls and no text content, this returns an empty string.

    But wait, the subagent should execute its tool calls and continue the loop. After executing the tool calls, the LLM should return a new response with text content. So the last assistant message should have text content.

    Unless... the subagent is not executing its tool calls! Let me think about why this might happen.

    Looking at the streaming.go code, when the LLM returns a response with tool calls, the handleStream function should correctly detect them and return a streamResult with Stopped: false. The runtime loop should then call processToolCalls to execute the tool calls.

    But what if the handleStream function is NOT correctly detecting the tool calls? Let me look at the code more carefully.

    Actually, I think I see the issue now! Let me look at the streaming.go code:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        ...
    }
    

    This condition checks if the finish reason is "stop" or "length". But what if LiteLLM sends finish_reason: "tool_calls"? In that case, this condition would NOT be true, and the code would continue processing the stream.

    But wait, the issue says the finish reason is "stop", not "tool_calls". So this should be handled correctly.

    Let me look at the code after the main loop:

    // After the loop ends (EOF or error)
    recordUsage()
    applyXMLFallback()
    ...
    return streamResult{
        Calls:             toolCalls,
        ...
        Stopped:           stoppedDueToNoOutput,
        FinishReason:      finishReason,
    }, nil
    

    So if the stream ends with EOF, the code should return the accumulated tool calls. But what if the tool calls are not accumulated correctly?

    Actually, I think I need to look at how the tool calls are accumulated. Let me look at the handleStream function more carefully.

    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,
                })
            }
            ...
        }
        continue
    }
    

    This looks correct. The tool calls are accumulated based on their ID.

    Hmm, let me think about this differently. Maybe the issue is not in how the tool calls are accumulated, but in how the streaming response is processed.

    Actually, I think I might have found the issue! Let me look at the OpenAI streaming adapter again:

    if a.trackUsage && (finishReasonStr == "stop" || finishReasonStr == "length") {
        finishReasonStr = ""
    }
    

    This line clears the finish reason when trackUsage is true and the finish reason is "stop" or "length". This is done because the usage information is sent in the last chunk, and the finish reason needs to be preserved for that chunk.

    But what if this is causing the issue? If the finish reason is cleared, the handleStream function might not correctly detect the end of the stream.

    Actually, looking at the code more carefully, I see that the finish reason is preserved in a.lastFinishReason:

    finishReason := chat.FinishReason(finishReasonStr)
    if finishReason != chat.FinishReasonNull && finishReason != "" {
        a.lastFinishReason = finishReason
    }
    

    And later, when the usage information is received:

    if openaiResponse.JSON.Usage.Valid() {
        ...
        finishReason := a.lastFinishReason
        if finishReason == chat.FinishReasonNull || finishReason == "" {
            finishReason = chat.FinishReasonStop
        }
        ...
    }
    

    So the finish reason should be correctly preserved. But wait, what if the usage information is NOT received? In that case, the finish reason would be cleared, and the handleStream function might not correctly detect the end of the stream.

    Actually, I think I see the issue now! Let me look at the condition for processing tool calls:

    if len(choice.Delta.ToolCalls) > 0 {
        ...
        continue
    }
    

    This continue statement skips the rest of the loop iteration. But what if the finish reason is sent in the SAME chunk as the tool calls? In that case, the finish reason would be skipped!

    Let me look at the streaming adapter code again:

    for i := range openaiResponse.Choices {
        choice := &openaiResponse.Choices[i]
        
        finishReasonStr := choice.FinishReason
        ...
     finishReason := chat.FinishReason(finishReasonStr)
        ...
        
        response.Choices[i] = chat.MessageStreamChoice{
            Index:        int(choice.Index),
            FinishReason: finishReason,
            Delta: chat.MessageDelta{
                Role:    choice.Delta.Role,
                Content: choice.Delta.Content,
            },
        }
        
        // Convert tool calls if present
        if len(choice.Delta.ToolCalls) > 0 {
            ...
        }
    }
    

    So the finish reason and tool calls are both included in the response. The handleStream function should process both.

    But wait, let me look at the handleStream function again:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        ...
        return streamResult{...}, nil
    }
    

    This condition checks the finish reason FIRST. If the finish reason is "stop", it returns immediately, BEFORE processing the tool calls!

    So if LiteLLM sends a chunk with BOTH finish_reason: "stop" AND tool calls, the tool calls would be ignored!

    Let me verify this by looking at the order of operations in handleStream:

    choice := response.Choices[0]
    
    // Check finish reason FIRST
    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        ...
        return streamResult{...}, nil
    }
    
    // Track the provider's explicit finish reason
    if choice.FinishReason != "" {
        providerFinishReason = choice.FinishReason
    }
    
    // Handle tool calls AFTER checking finish reason
    if len(choice.Delta.ToolCalls) > 0 {
        ...
    }
    

    Yes! This is the bug! If the finish reason is "stop" and the tool calls are in the same chunk, the tool calls are ignored.

    Actually wait, let me re-read the condition:

    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,
            ...
            Stopped:           len(toolCalls) == 0,
            FinishReason:      finishReason,
        }, nil
    }
    

    It checks len(toolCalls) > 0, which is the ACCUMULATED tool calls from PREVIOUS chunks. So if the tool calls were sent in PREVIOUS chunks, they would be correctly detected.

    But what if the tool calls are sent in the SAME chunk as the finish reason? In that case, toolCalls would be empty (because the tool calls haven't been processed yet), and the function would return with no tool calls!

    This is the bug! LiteLLM might be sending the tool calls and the finish reason in the same chunk, which causes the tool calls to be ignored.

    Actually, I need to verify this. Let me look at the OpenAI streaming format. In the standard OpenAI API, tool calls are sent in separate chunks before the finish reason. But LiteLLM might be sending them differently.

    Let me also check if there's a continue statement after processing tool calls:

    if len(choice.Delta.ToolCalls) > 0 {
        ...
        continue
    }
    

    Yes, there's a continue statement. So if the tool calls are processed, the loop continues to the next iteration, and the finish reason is processed in the next iteration.

    But if the finish reason and tool calls are in the SAME chunk, the finish reason is processed FIRST, and the tool calls are IGNORED.

    This is the bug!

    Actually, let me double-check by looking at the order of operations more carefully:

    1. Check if choice.FinishReason is "stop" or "length"
    2. If yes, return immediately with the accumulated tool calls
    3. If no, check if there are tool calls in the delta
    4. If yes, accumulate them and continue

    So the issue is that if the finish reason and tool calls are in the same chunk, the finish reason is processed first, and the tool calls are ignored.

    The fix would be to process the tool calls BEFORE checking the finish reason.

    Actually wait, I need to think about this more carefully. In the standard OpenAI API, the tool calls are sent in separate chunks, and the finish reason is sent in the last chunk (with empty delta). So the tool calls are accumulated BEFORE the finish reason is processed.

    But LiteLLM might be sending them differently. If LiteLLM sends the tool calls and the finish reason in the same chunk, the tool calls would be ignored.

    Let me verify this by looking at the OpenAI streaming format more carefully.

    Actually, I think I need to look at the code more carefully. Let me look at the handleStream function again:

    for {
        response, err := stream.Recv()
        ...
        
        choice := response.Choices[0]
        
        if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
            ...
            return streamResult{...}, nil
        }
        
        ...
        
        if len(choice.Delta.ToolCalls) > 0 {
            ...
            continue
        }
        
        ...
    }
    

    So the order is:

    1. Check finish reason
    2. If finish reason is "stop" or "length", return immediately
    3. Otherwise, process tool calls

    If the finish reason and tool calls are in the same chunk, the finish reason is processed first, and the tool calls are ignored.

    But wait, in the standard OpenAI API, the finish reason is NOT sent with the tool calls. The tool calls are sent in separate chunks, and the finish reason is sent in the last chunk (with empty delta).

    So the issue is specific to LiteLLM, which might be sending the finish reason and tool calls in the same chunk.

    The fix would be to process the tool calls BEFORE checking the finish reason. Or, more precisely, to check the finish reason AFTER processing the tool calls.

    Actually, I think the fix is simpler. We should process the tool calls in the same chunk as the finish reason, and then return the result. Let me think about how to implement this.

    The fix would be to move the tool call processing BEFORE the finish reason check:

    // Handle tool calls FIRST
    if len(choice.Delta.ToolCalls) > 0 {
        ...
        continue
    }
    
    // Check finish reason AFTER processing tool calls
    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        ...
        return streamResult{...}, nil
    }
    

    But wait, this would change the behavior for the standard OpenAI API. In the standard OpenAI API, the finish reason is sent in a separate chunk (with empty delta), so this change wouldn't affect it.

    Actually, I think the fix is even simpler. We should process the tool calls in the same chunk as the finish reason, and then check if the finish reason is "stop" or "length". If it is, we return the result.

    Let me implement this fix:

    // Handle tool calls FIRST
    if len(choice.Delta.ToolCalls) > 0 {
        ...
    }
    
    // Check finish reason AFTER processing tool calls
    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        ...
        return streamResult{...}, nil
    }
    

    But wait, this would change the behavior. In the original code, if the finish reason is "stop" and there are no tool calls, the function returns immediately. With this change, it would continue processing the chunk (which has no tool calls), and then return.

    Actually, I think the original code is correct for the standard OpenAI API. The issue is specific to LiteLLM, which sends the finish reason and tool calls in the same chunk.

    The fix should be to process the tool calls BEFORE checking the finish reason, but only if the finish reason is "stop" or "length". If the finish reason is something else (like "tool_calls"), we should process the tool calls and continue.

    Actually, I think the simplest fix is to move the tool call processing BEFORE the finish reason check, and remove the continue statement. This way, the tool calls are always processed, and the finish reason is checked after.

    Let me implement this fix in streaming.go.

    Actually, I just realized something. The issue might be even simpler. Let me look at the OpenAI streaming adapter again:

    if a.trackUsage && (finishReasonStr == "stop" || finishReasonStr == "length") {
        finishReasonStr = ""
    }
    

    This clears the finish reason when trackUsage is true. But what if the finish reason is "tool_calls"? In that case, the finish reason would NOT be cleared, and the handleStream function would process it correctly.

    But the issue says the finish reason is "stop", not "tool_calls". So the finish reason would be cleared, and the handleStream function might not correctly detect the end of the stream.

    Actually, looking at the code more carefully, I see that the finish reason is preserved in a.lastFinishReason:

    finishReason := chat.FinishReason(finishReasonStr)
    if finishReason != chat.FinishReasonNull && finishReason != "" {
        a.lastFinishReason = finishReason
    }
    

    And later, when the usage information is received:

    if openaiResponse.JSON.Usage.Valid() {
        ...
        finishReason := a.lastFinishReason
        ...
    }
    

    So the finish reason should be correctly preserved. But wait, what if the usage information is NOT received? In that case, the finish reason would be cleared, and the handleStream function might not correctly detect the end of the stream.

    Actually, I think the issue is in how the streaming adapter handles the finish reason. Let me look at the code more carefully.

    OK, I think I've been overthinking this. Let me focus on the specific issue:

    1. LiteLLM sends a response with tool calls and finish_reason: "stop"
    2. The subagent's handleStream function processes the response
    3. The host agent reports "no response from subagent"

    The issue is that the subagent's handleStream function is not correctly processing the tool calls.

    Let me look at the streaming.go code one more time:

    if choice.FinishReason == chat.FinishReasonStop || choice.FinishReason == chat.FinishReasonLength {
        ...
        return streamResult{
            Calls:             toolCalls,
            ...
            Stopped:           len(toolCalls) == 0,
            FinishReason:      finishReason,
        }, nil
    }
    

    If the finish reason is "stop" and the tool calls are in the same chunk, toolCalls would be empty (because the tool calls haven't been processed yet), and the function would return with no tool calls.

    This is the bug!

    The fix is to process the tool calls BEFORE checking the finish reason.

    Let me implement this fix.

    Wait, actually I need to re-examine. Let me look at the condition 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{
            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
    }
    

    So if toolCalls is empty (because the tool calls are in the same chunk but haven't been processed yet), the function returns with Stopped: true (because len(toolCalls) == 0), which means the runtime loop would stop instead of executing the tool calls.

    This is the bug!

    The fix is to process the tool calls BEFORE checking the finish reason.

    Let me implement this fix now.

  35. Assistant

    Now I can see the key issue. Let me look more closely at the flow. The problem is that in handleStream, when a chunk has FinishReason == "stop", it returns immediately BEFORE processing tool calls in that same chunk. But more importantly, the issue is about the subagent's tool_calls response not being handled. Let me look more carefully at the MCP server that says "No response from agent":

  36. Assistant

    Let me look at the MCP server to understand the context:

  37. Assistant

    Now I see the MCP server uses sess.GetLastAssistantMessageContent() and falls back to "No response from agent". Let me also look at the a2a adapter:

  38. Assistant

    Let me understand the streaming flow better. Let me look at where the OpenAI stream adapter is created:

  39. Assistant

    Let me look at how trackUsage is determined:

  40. Assistant

    Let me find where trackUsage is determined in the client:

  41. Assistant

    Now I'm getting closer to understanding the issue. The key is in handleStream in streaming.go. When a chunk contains BOTH tool_calls AND finish_reason: "stop" (which LiteLLM proxy may do), the finish_reason check fires BEFORE the tool_calls are accumulated, causing them to be lost. Let me verify this by looking at the exact code flow:

  42. Assistant

    Now I see the bug clearly! In handleStream, the finish_reason check at line 133 fires BEFORE the tool_calls are accumulated at line 160. If a streaming chunk contains BOTH finish_reason: "stop" AND tool_calls in the delta (which LiteLLM proxy does), the tool calls are lost. Let me also check how the adapter handles this:

  43. Assistant

    Now I fully understand the bug. Let me trace through the issue:

    1. With trackUsage=true (default): When LiteLLM sends usage + tool_calls + finish_reason: "stop" in the same chunk, the adapter strips "stop" but then re-synthesizes it from the usage handling, setting Choices[0].FinishReason = "stop". Then handleStream sees "stop" and returns before processing tool_calls in the delta.

    2. With trackUsage=false: The "stop" finish_reason is preserved, same problem.

    The fix is to move tool call processing BEFORE the finish_reason check in handleStream. Let me first look at the existing tests to understand what's tested:

  44. Assistant

    Let me look at the existing streaming tests to understand the test patterns:

  45. Assistant

    Let me search for streaming test files more broadly:

  46. Assistant

    Let me look at the oaistream adapter test:

  47. Assistant

    Let me also check if there's a test for handleStream:

  48. Assistant

    Let me look for streaming test files in the runtime package:

  49. Assistant

    Let me also look at the tool choice responses test:

  50. Assistant

    Now I understand the bug. Let me create a test to reproduce the issue first:

  51. Assistant

    Now let me implement the fix. The key change is to move tool call processing BEFORE the finish_reason check in handleStream:

  52. Assistant

    Let me see the full tool call processing block:

  53. Assistant

    Now I need to implement the fix. The approach is to move tool call processing BEFORE the finish_reason check, and use a flag to skip content processing when tool calls were handled. Let me make the edit:

  54. Assistant

    Now let me make the edit to fix the issue. I need to move the tool call processing before the finish_reason check:

  55. Assistant

    Let me use the edit command instead to make the changes directly. First, let me see the exact lines I need to modify:

  56. Assistant

    Now I need to replace the section from line 128 to 220 (where continue is) with my new code. Let me see what comes after line 220:

  57. Assistant

    Now let me make the edit. I'll replace lines 128-212 with the fixed code:

  58. Assistant

    Now let me check that the rest of the code is correct:

  59. Assistant

    I see there are duplicate lines. The edit added the new code but the old code is still there. Let me fix this by removing the duplicate lines:

  60. Assistant

    Let me verify the file is correct by looking at the whole function:

  61. Assistant

    Good, the file looks correct now. Let me verify the key section of the change:

  62. Assistant

    Good, the fix looks correct. Now let me run the existing tests to make sure nothing is broken:

  63. Assistant

    Let me check the Go environment:

  64. Assistant

    Let me check the GOPATH and GOMODCACHE settings:

  65. Assistant

    Let me check if there's a go environment setup script:

  66. Assistant

    Let me set up the environment properly.

  67. Assistant

    Let me run the full runtime tests:

  68. Assistant

    The runtime tests are failing, but these look like pre-existing failures (context window overflow errors). Let me check if these are pre-existing:

  69. Assistant

    Let me check which specific test is failing:

  70. Assistant

    Let me check which tests actually fail:

  71. Assistant

    Let me check if this test was failing before my change:

  72. Assistant

    Good, the test was already failing before my change. Let me restore my changes:

  73. Assistant

    Now let me run the oaistream adapter tests:

  74. Assistant

    Good, all oaistream tests pass. Now let me also check that the code compiles correctly:

  75. Assistant

    Good, the code compiles. Let me also run the full test suite for the runtime package (excluding the pre-existing failure):

  76. Assistant

    All tests pass (except the pre-existing failure). Let me also run a broader set of tests to make sure nothing else is broken:

  77. Assistant

    Let me check if those failures are pre-existing:

  78. Assistant

    Good, the TestDoCompactAfterHookFires failure is pre-existing. Let me restore my changes:

  79. Assistant

    Now let me also check if there's an issue in the adapter that might need fixing too. Let me look at the adapter's handling of the usage chunk when tool_calls are present:

  80. Assistant

    Now let me also consider if there's an issue in the adapter itself. When trackUsage is true and LiteLLM sends usage + tool_calls + finish_reason: "stop" in the same chunk:

    1. The adapter strips "stop" (since trackUsage is true)
    2. Tool calls are populated in the delta
    3. Usage handling re-synthesizes "stop" as the finish reason
    4. Returns with BOTH FinishReason: "stop" AND ToolCalls

    With my fix in handleStream, this is now handled correctly because tool calls are accumulated BEFORE the finish reason check. But I should also consider if the adapter should be smarter about this. Let me check if there's a case where the adapter strips "stop" but the usage chunk comes separately (standard OpenAI behavior):

  81. Assistant

    Good, the adapter's behavior is fine - it correctly passes through tool_calls. The issue is solely in handleStream. Now let me also run the full build to make sure everything compiles:

  82. Assistant

    Good, everything compiles. Let me now look at the final diff to verify my changes:

  83. Assistant

    The diff looks correct. The key changes are:

    1. Tool call processing moved BEFORE the finish_reason check
    2. handledToolCalls flag used to skip content processing when tool calls were in the chunk
    3. The continue statement removed (replaced by the flag-based approach)

    Let me now run the full test suite one more time to make sure everything is working:

  84. Assistant

    Let me check if any of those tests failed:

  85. Assistant

    Let me fix the grep command:

  86. Assistant

    All tests pass. Let me also run the oaistream tests to make sure they still pass:

  87. Assistant

    All tests pass. Now let me verify my understanding of the issue by looking at the full picture one more time:

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.