← Back to Pull requests

fix(llminternal): run the tool callbacks for streaming tools #2485

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 24, 2026 03:56 UTC
Author

Linked issue

  • Closes: #2452

  • Related: #1515 (the same bug, closed without a fix), #2274 (runs OnToolError and

  • AfterTool for a failed streaming tool; this change covers that case too, so the two
    overlap in base_flow.go)

    Describe the change:

    Problem:

    handleFunctionCalls sends a StreamingFunctionTool straight to RunStream, in live mode
    and outside it (internal/llminternal/base_flow.go L1613-L1668 before this change). Only
    plain function tools reach callTool (L1677), which is where the agent and plugin
    BeforeTool, AfterTool and OnToolError callbacks run.

    So a BeforeToolCallback that refuses a call or rewrites its arguments has no effect on a
    tool built with functiontool.NewStreaming, and a plugin that uses the tool callbacks for
    authorization or argument checks does not cover streaming tools. ToolCallIntegrityPlugin
    lists streaming tools as unchecked for this reason.

    Solution:

    Streaming tools now go through the same pipeline as plain function tools:

  • the before-tool callbacks run first, and if one answers the call or returns an error the

  • tool never runs — in live mode the streaming task is never registered or started;
  • a non-live call's outcome, result or error, passes through the on-tool-error and

  • after-tool callbacks;
  • in live mode the after-tool callbacks see the pending-result placeholder, and one that

  • fails the call stops the stream before it starts.

    The live call is registered with the session before the after-tool callbacks run, so a
    stop_streaming issued in the same batch of function calls still finds it, and the
    registration is removed again if a callback then fails the call.

    finishToolCall is split into a finishToolCallResult that returns the response and the
    error, with finishToolCall keeping the final step of turning an error into a function
    response. The live path needs the error itself to decide whether to start the stream; the
    two existing callers are unchanged.

    Behavior change

    For someone on the current release who has no tool callbacks and no plugin that uses
    them: nothing changes. finishToolCall returns the response unchanged when nothing is
    registered, and the error path produces the same {"error": <ModelErrorText>} map it did
    before.

    For someone who does have tool callbacks or such a plugin: their callbacks now fire for
    streaming tools, where they were silently skipped before. A BeforeToolCallback that
    returns a result or an error now stops a streaming tool from running, including a live one;
    an AfterToolCallback now sees streaming results, including the live pending placeholder,
    and can replace them. That is the point of the fix, but it is an observable change for
    anyone who had written callbacks that assumed streaming tools were exempt.

    Testing Plan

    Unit Tests:

  • All unit tests pass locally.
  • TestHandleFunctionCalls_StreamingToolCallbacks in
    internal/llminternal/streaming_tool_test.go, seven subtests:

    | Subtest | Pins |
    | --- | --- |
    | before-tool callback answers instead of the tool | the call is answered, the stream never runs |
    | before-tool callback fails the call | the error reaches the model, the stream never runs |
    | before-tool callback rewrites the arguments | the stream runs with the rewritten args |
    | after-tool callback sees the result | the aggregated result reaches the callback and can be replaced |
    | on-tool-error callback answers a failing stream | a stream error reaches the callback |
    | live mode: before-tool callback keeps the stream from starting | no chunk is sent to the live session |
    | live mode: after-tool callback sees the pending status | the placeholder reaches the callback |

    TestHandleFunctionCalls_LiveStreamingToolAfterCallback, against a real
    liveSessionImpl, two subtests:

    | Subtest | Pins |
    | --- | --- |
    | registered while the after-tool callbacks run | the call is registered before those callbacks, so a stop_streaming in the same batch still finds it |
    | after-tool callback failure keeps the stream from starting | the tool never runs and the registration is removed |

    With your source change reverted and your tests kept, which test fails?

    All nine. Each new branch was also mutated on its own to confirm the tests pin it and not
    just the headline fix:

  • dropping the before-callback short circuit → the 3 before-tool subtests fail;

  • live pending not passed through the after-tool callbacks → the pending-status subtest fails;

  • non-live error not passed through finishToolCall → the on-tool-error subtest fails;

  • non-live success not passed through finishToolCall → the after-tool subtest fails;

  • live after-tool error no longer stopping the stream → the after-tool-failure subtest fails;

  • registering after the after-tool callbacks instead of before → the registration subtest fails.
  • Full run, both modules, per AGENTS.md:

    go build -mod=readonly ./...                       # both modules, clean
    go test -race -mod=readonly -count=1 -shuffle=on ./...   # both modules, all ok
    golangci-lint run                                  # v2.15.0, "0 issues." in both modules
    go mod tidy -diff                                  # no output in both modules
    

    Manual End-to-End (E2E) Tests:

    Not run against a live model. This change is internal flow control: it touches no request
    or response conversion, no model backend and no outbound integration, so there is nothing
    for a live run to exercise that the tests do not. The live path is covered through
    mockLiveSession.

    Checklist

  • I have read the CONTRIBUTING.md document.

  • I have performed a self-review of my own code. (Fresh-context pass per AGENTS.md; it found the two live-path issues above, which this branch fixes.)

  • I have commented my code, particularly in hard-to-understand areas.

  • I have added tests that prove my fix is effective or that my feature works.

  • New and existing unit tests pass locally with my changes.

  • I have manually tested my changes end-to-end. (See above: no live model run; internal flow control only.)

  • Any dependent changes have been merged and published in downstream modules.
  • Additional context

    Parity with adk-python, checked file by file:

  • _launch_function_call_live runs a streaming tool through

  • _execute_single_prepared_call with defer_stream as the tool runner and starts the
    stream only after that call returns, so a before-tool callback that answers leaves
    stream_context unset and the stream never starts
    (src/google/adk/flows/llm_flows/tools/_live_caller.py L500-L545).
  • defer_stream returns _pending_response() (_live_caller.py L519-L523, L147-L153),

  • which is what the after-tool callbacks are handed (_caller.py L617-L632). That is why
    the live placeholder goes through them here, with the same text.
  • An after_tool_callback that raises propagates out of

  • _execute_single_prepared_call, is caught by _background_task (_live_caller.py
    L544), and the if stream_context is not None block at L537 is never reached — the
    stream does not start. This change does the same for a callback that returns an error.
  • The background-tool entry is added synchronously when the task is created

  • (_live_caller.py L567-L583), before the callbacks run, which is why registration here
    happens before the after-tool step.
  • _caller.py runs the plugin and the canonical before-tool callbacks before the tool

  • (L522-L541).

    One thing adk-python does that this does not: it applies apply_confirmation_gate before
    the tool runner for live streaming tools (_caller.py L580-L585), where ADK Go relies on
    the tool's own check inside RunStream. That gap predates this change and is left alone.

    On #2274 and @ktsoator's offer. #2274 covers the failure half of this (OnToolError and
    AfterTool for a failed streaming tool) and currently has conflicts; this change covers the
    same ground plus BeforeTool and the success path, so one of the two should give way — happy
    for it to be this one if the maintainers prefer. @ktsoator offered on #2452 to pick up the
    BeforeTool part; I had this branch ready and did not want to sit on it, so please treat this
    as something to take over or build on rather than a land grab.

    AI disclosure. I used Claude Code to locate the bug, write the fix and the tests, run
    the mutation checks, and draft this description. I reviewed the change and ran everything
    above myself.

    🤖 Generated with Claude Code

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: ktsoator Review duration: 9554m
    All Vouch review confidence checks passed
    Residual risk 0.33 = Change Risk (0.57) × (1 − Review Confidence (0.43)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.57 · 650 lines diff across 8 files
    0.57
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    1 comments
    "Review active on #2485"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 43.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 57% (MEDIUM) · Higher = larger blast radius
    57%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 43.0% · Lower = rushed or shallow review
    43.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 32.5% · Safe to merge
    32.5%
    Repository