spring-ai icon indicating copy to clipboard operation
spring-ai copied to clipboard

Removal of `streamToolCallResponses` broke tool calling manager

Open EgbertW opened this issue 4 months ago • 7 comments

Commit: https://github.com/spring-projects/spring-ai/commit/a753fde6c23cf1912104b9d833467b624e9c50d2 broke our advisor / agent because it does not forward AssistantMessage with tool_calls anymore.

Bug description streamToolCallResponses was removed without a proper replacement. Documented in the notes: https://docs.spring.io/spring-ai/reference/upgrade-notes.html#_removed_streamtoolcallresponses_from_advisor_builders_and_auto_configuration

Our agent relies on this exact behavior and is now broken - forcing us to copy and adjust the source code of ToolCallingAdvisor to do this differently.

Our flow involves forwarding all tool calls from LLM to the client and also all tool responses. The tool responses are hooked together with the corresponding tool_call, but now that the tool_calls are filtered out in streamWithToolCallResponses they never reach the client which therefore drops it.

To make matters worse, streamWithToolCallResponses is private so we cannot override it.

Environment spring-ai 2.0.0

Steps to reproduce Create a client, expect to receive tool_calls in assistant messages.

Expected behavior Ideally, I would expect it to be configurable to:

  • Forward or drop AssistantMessages with tool_calls
  • Forward or drop ToolResponse messages

Right now it's very opinionated: AssistantMessage with tool calls is dropped, no way to change this without implementing your own ToolCallingAdvisor. ToolResponse is forwarded ONLY when it is set returnDirect.

The latter we can overcome via ToolCallingManager implementation, but the former we cannot.

EgbertW avatar Jul 14 '26 11:07 EgbertW

i would like to work on this issue

Tejashribambal19 avatar Jul 14 '26 16:07 Tejashribambal19

Same as #6435.

TonyJeans avatar Jul 15 '26 14:07 TonyJeans

In a way @TonyJeans - however, I'm not requesting the Tool Execution Callback API. I'm merely requesting the revert of a removal that breaks stuff :) Especially until there is a viable alternative, which this proposed callback API definitely would be.

My report is focused at the removal of the streamToolCallResponses that did the job just fine before. In certain use cases it could perhaps give confusing responses (although to me it doesn't seem like a hard requirement in a streaming context to have the tool call and tool response in the same update, but that's a different discussion). I expect that's why it was a flag. The removal of this flag breaks things without giving an alternative which I consider to be a bug.

My proposed intermediate solution would be the reintroduction of this flag / revert of the offending commit.

EgbertW avatar Jul 15 '26 18:07 EgbertW

I've been reading the ToolCallingAdvisor code and the related #6435 discussion.

The simplest fix seems to be reintroducing a streamToolCallResponses flag on the Builder that controls the .filter() in streamWithToolCallResponses() (defaulting to false for backward compatibility).

The change would be minimal:

// Builder field (default preserves current behavior):
private boolean streamToolCallResponses = false;

// In streamWithToolCallResponses(), make the filter conditional:
.filter(ccr -> this.streamToolCallResponses
    || !this.toolExecutionEligibilityChecker.isToolCallResponse(ccr.chatResponse()));

The alternative (ObservationHandler) mentioned by @ThomasVitale in #6435 addresses monitoring/tracing but doesn't solve the client-facing streaming use case here — the client needs the tool call messages in the actual Flux, not just in observation traces.

Happy to submit a PR if this approach is acceptable.

sumitvairagar avatar Jul 17 '26 07:07 sumitvairagar

@EgbertW Thanks for the report and others for chiming in with the insights.

Introducing the flag approach could impact the original issue of corrupting the conversation history https://github.com/spring-projects/spring-ai/commit/a753fde6c23cf1912104b9d833467b624e9c50d2

We are currently discussing a potential alternative including the ObservationHandler. We'll update here with the outcome. Thanks!

ilayaperumalg avatar Jul 20 '26 12:07 ilayaperumalg

@ilayaperumalg Understood. thanks for the update. Will pick up something else.

sumitvairagar avatar Jul 20 '26 14:07 sumitvairagar

10. @EgbertW Thanks for the report and others for chiming in with the insights. Introducing the flag approach could impact the original issue of corrupting the conversation history a753fde We are currently discussing a potential alternative including the ObservationHandler. We'll update here with the outcome. Thanks!

@ilayaperumalg @zz-zhi54

Hi, and thank you to the Spring AI team for your support.

I’ve seen some suggestions from the community about using an ObservationHandler: https://github.com/spring-ai-community/spring-ai-agent-utils/blob/main/docs/tools/ToolCallListener.md spring-ai-community/spring-ai-agent-utils#84

I’d also like to add that, in practice, we usually need observation support for returnDirect, subagents, and human-in-the-loop interactions as well. I currently handle these cases through a custom ToolCallingManager.

The custom event protocol I use is shown below:

Image

What excites me is that Spring AI has also implemented human-in-the-loop—that’s great.

https://github.com/spring-projects/spring-ai/issues/6916 https://github.com/spring-projects/spring-ai/pull/7157

//[[Human-in-the-loop and the distinction between subagent thinking and replies have also been added to SSE.]]
package com.example.chat.api.dto;

import com.fasterxml.jackson.annotation.JsonInclude;

import java.util.List;
import java.util.Map;

/**
 * A structured event in a streaming response, corresponding to one SSE data event.
 * Possible values of {@code type} include:
 * <ul>
 *   <li>{@code token} / {@code reasoning} - Text or reasoning deltas, stored in {@link #data}.</li>
 *   <li>{@code tool_call} / {@code tool_result} - Tool calls and results, stored in
 *       {@link #toolCalls} / {@link #toolResults}.</li>
 *   <li>{@code approval_request} - Emitted when a Spring AI confirmation policy requires
 *       human approval. {@link #data} contains the request ID, which is submitted to
 *       {@code POST /chat/approval}. {@link #toolCalls} contains the tool awaiting approval.
 *       If no response is received before the timeout, the request defaults to DECLINE.</li>
 *   <li>{@code question_request} - Emitted when the main agent needs additional information
 *       from the user. {@link #data} contains the request ID, while {@code questions} in
 *       {@link #args} contains the structured question list. Answers are submitted to
 *       {@code POST /chat/question/answer}.</li>
 *   <li>{@code finish} / {@code error} - Completion, with {@link #reason} and optional
 *       {@link #usage}, or an error message in {@link #data}.</li>
 *   <li>{@code heartbeat} - An SSE keep-alive event with no business payload, ignored by
 *       the frontend.</li>
 * </ul>
 *
 * Subagents use the corresponding
 * {@code subagent_start/token/reasoning/tool_call/tool_result/approval_request/finish}
 * events. {@code name} identifies the subagent, and the remaining fields have the same
 * meaning as their main-agent counterparts. Approval responses use the same endpoint.
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public record ChatEvent(
        String type,
        String data,
        String name,
        Map<String, Object> args,
        String reason,
        Map<String, Object> usage,
        List<ToolCallRef> toolCalls,
        List<ToolResultRef> toolResults
) {

    public record ToolCallRef(String id, String name, String arguments) {}

    public record ToolResultRef(String id, String name, String result) {}

    public record QuestionRef(
            String question,
            String header,
            List<QuestionOptionRef> options,
            boolean multiSelect
    ) {
        public QuestionRef {
            options = List.copyOf(options);
        }
    }

    public record QuestionOptionRef(String label, String description) {}

    public static ChatEvent token(String text) {
        return new ChatEvent("token", text, null, null, null, null, null, null);
    }

    public static ChatEvent reasoning(String text) {
        return new ChatEvent("reasoning", text, null, null, null, null, null, null);
    }

    public static ChatEvent toolCall(List<ToolCallRef> calls) {
        return new ChatEvent("tool_call", null, null, null, null, null, calls, null);
    }

    public static ChatEvent toolResult(List<ToolResultRef> results) {
        return new ChatEvent("tool_result", null, null, null, null, null, null, results);
    }

    /**
     * Creates a HITL approval request event. The request ID is stored in {@link #data}
     * and returned unchanged by the frontend through {@code POST /chat/approval}.
     * The tool awaiting approval is represented as a single-element {@link ToolCallRef}
     * list, using the same structure as a regular {@code tool_call} event.
     */
    public static ChatEvent approvalRequest(
            String requestId,
            String toolCallId,
            String name,
            String arguments
    ) {
        return new ChatEvent(
                "approval_request",
                requestId,
                null,
                null,
                null,
                null,
                List.of(new ToolCallRef(toolCallId, name, arguments)),
                null
        );
    }

    /**
     * Creates an interactive question event. The frontend must return {@code data}
     * unchanged as the request ID.
     */
    public static ChatEvent questionRequest(
            String requestId,
            List<QuestionRef> questions
    ) {
        return new ChatEvent(
                "question_request",
                requestId,
                null,
                Map.of("questions", List.copyOf(questions)),
                null,
                null,
                null,
                null
        );
    }

    public static ChatEvent finish(String reason, Map<String, Object> usage) {
        return new ChatEvent("finish", null, null, null, reason, usage, null, null);
    }

    public static ChatEvent error(String message) {
        return new ChatEvent("error", message, null, null, null, null, null, null);
    }

    /**
     * Creates an SSE keep-alive event with no business payload. During long-running
     * HITL waits, these events are sent periodically to trigger proxy buffer flushing.
     */
    public static ChatEvent heartbeat() {
        return new ChatEvent("heartbeat", null, null, null, null, null, null, null);
    }

    public static ChatEvent subagentStart(String name, String prompt) {
        return new ChatEvent(
                "subagent_start", prompt, name, null, null, null, null, null
        );
    }

    public static ChatEvent subagentToken(String name, String text) {
        return new ChatEvent(
                "subagent_token", text, name, null, null, null, null, null
        );
    }

    public static ChatEvent subagentReasoning(String name, String text) {
        return new ChatEvent(
                "subagent_reasoning", text, name, null, null, null, null, null
        );
    }

    public static ChatEvent subagentToolCall(
            String name,
            List<ToolCallRef> calls
    ) {
        return new ChatEvent(
                "subagent_tool_call", null, name, null, null, null, calls, null
        );
    }

    public static ChatEvent subagentApprovalRequest(
            String name,
            String requestId,
            String toolCallId,
            String toolName,
            String arguments
    ) {
        return new ChatEvent(
                "subagent_approval_request",
                requestId,
                name,
                null,
                null,
                null,
                List.of(new ToolCallRef(toolCallId, toolName, arguments)),
                null
        );
    }

    public static ChatEvent subagentToolResult(
            String name,
            List<ToolResultRef> results
    ) {
        return new ChatEvent(
                "subagent_tool_result", null, name, null, null, null, null, results
        );
    }

    public static ChatEvent subagentFinish(String name, String reason) {
        return new ChatEvent(
                "subagent_finish", null, name, null, reason, null, null, null
        );
    }
}

If you need to learn about this example, you can refer to the full demo :

https://github.com/git-syl/hermes-agent-demo/blob/main/README.en.md

git-syl avatar Oct 22 '26 14:10 git-syl