#5960·pipecat

Make the post-tool LLM run race-free when the tool result beats UserStoppedSpeakingFrame

Author: SwAt1563Created Sep 28, 2026Updated Sep 30, 2026

Problem Statement

Follow-up to #5823, with evidence from real sessions and the workaround we now run.

With turn completion on, a tool call closes the user's turn. UserTurnCompletionLLMServiceMixin broadcasts turn completion on FunctionCallsStartedFrame, and the comment there says this "gives UserStoppedSpeakingFrame maximum time to propagate so the assistant aggregator's _user_speaking is False by the time a FunctionCallResultFrame arrives" (turns/user_turn_completion_mixin.py:475-480 in 1.12.0).

A head start doesn't guarantee the order. With a fast local tool, the result can reach LLMAssistantAggregator before the UserStoppedSpeakingFrame from the same turn close. _user_speaking is still True there, so this check skips the run (processors/aggregators/llm_response_universal.py:2026 in 1.12.0):

python
if run_llm and not self._user_speaking:
    await self._maybe_push_context_after_function_result()

The run is left to the end of the user's turn. That turn has already ended, and nothing checks again when UserStoppedSpeakingFrame arrives a few ms later. No LLM run ever sees the tool result, and the bot stays silent until the user speaks again. In a voice call it looks like the agent froze right after the user answered.

Evidence (pipecat 1.11.0, redacted log excerpt attached). The tool, get_gate_notions, is a local dictionary lookup that returns in a few ms. Two calls in the same session:

Time (UTC) User aggregator closes the turn Assistant aggregator gets the result Post-tool run Outcome
16:25:09 .771 .775 (+4 ms) Pushing context frame! Bot replied about 2 s later
16:26:18 .216 .218 (+2 ms) none 87 s of silence, until the user asked "So did you hear me?" at 16:27:45

The session log has no More FunctionCallResultFrames queued or Bot is speaking — deferring line at all, so the _user_speaking check is the only branch that could have skipped the second run.

Proposed Solution

We run a workaround: two small subclasses of the universal aggregators (post_tool.py, attached and below). We would rather this lived in pipecat, and we'd like you to check that the approach is right.

What it does

  1. It reads the turn from the paired user aggregator. The turn counts as pending while _user_turn_controller._user_turn is True, and also after the turn closes until on_user_turn_stopped has fired, because its words may not be in the context yet. _user_speaking is overridden to always return False, so pipecat's checks that read it fall through to this one.
  2. A run that has to wait is kept as owed. When a result wants a run and the turn is pending, the run is marked owed instead of being dropped.
  3. The owed run is sent when the turn closes. In on_user_turn_stopped, once the turn's words are written: if the run is still owed and no new turn is pending, push the context.
  4. Any other run cancels it. A context push from either aggregator after the result already sees the result. That covers the user's own end-of-turn inference, a ◐/○ re-prompt and pipecat's empty-turn reply. So any push clears the owed run and _push_context_on_bot_stopped_speaking, and this is what prevents a second reply.
  5. The bot-stopped deferral checks the same turn state. With _user_speaking forced to False, a deferred run would otherwise start at BotStoppedSpeakingFrame even if the user had just started a new turn, which happens when the bot finishes naturally at that moment. So at bot-stop, if a turn is pending, the deferral is cleared and the run stays owed until that turn closes.

On 1.12.0 an empty turn also sends the owed run, because pipecat's empty-turn reply declines after max_consecutive_recoveries (default 1). When that reply does run, rule 4 cancels the owed run, so the result still gets exactly one run.

The workaround relies on private members (_user_turn_controller._user_turn, _push_context_on_bot_stopped_speaking, _maybe_push_context_after_function_result). We enable it only on the exact pipecat release our check has passed on, and use pipecat's own classes otherwise.

How it could look in pipecat. LLMAssistantAggregator already has _paired_user_aggregator, so this can be native:

  • LLMUserAggregator exposes whether the user turn is pending: open, or closed but not yet written to the context.
  • _handle_function_call_result marks the run owed when the paired turn is pending, instead of skipping it.
  • The owed run is pushed when the paired turn stops, after the context write. Any push_context_frame from either aggregator clears it.
  • The bot-stopped deferral waits while a user turn is pending.

What we'd like you to check

  • Is "open, or closed but not yet written" the right definition of the user still having the floor?
  • Rule 4 assumes that every context push after the result includes it. Is there a push where that isn't true?
  • We don't use speculative turns or realtime mode and haven't tested either.

Status. We deployed this on 26 September. In 3 real sessions since then, the silence hasn't come back. That is a small sample, so if it happens again with this in place, I'll add the logs here.

post_tool.py (current version, pipecat 1.12.0)
python
from loguru import logger
from pipecat.frames.frames import BotStoppedSpeakingFrame, Frame
from pipecat.processors.aggregators.llm_response_universal import (
    LLMAssistantAggregator,
    LLMUserAggregator,
)
from pipecat.processors.frame_processor import FrameDirection


class PostToolUserAggregator(LLMUserAggregator):
    """Tells the assistant half each time it asks the LLM to run."""

    assistant: "PostToolAssistantAggregator | None" = None

    async def push_context_frame(self, direction=FrameDirection.DOWNSTREAM):
        if self.assistant:
            self.assistant.run_requested()
        await super().push_context_frame(direction)


class PostToolAssistantAggregator(LLMAssistantAggregator):
    """Make sure a tool result always gets its LLM run (pipecat#5823).

    Pipecat holds the post-tool run while the learner's turn is open and leaves
    it to that turn, but it reads the turn from UserStarted/StoppedSpeakingFrame,
    which arrive a few ms late, and it never retries. A tool call is what closes
    the learner's turn, so its result races that frame. On 25 Sept the result
    won by 2ms, and Eva said nothing for 87s.

    Here the turn itself is checked. A held run is owed until the turn has closed
    and written its words, then it runs, unless another run was asked for in
    between (that run already sees the result).

    Delete both classes once pipecat#5823 is fixed upstream.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._run_owed = False
        self._turn_written = True
        user = self._paired_user_aggregator
        user.assistant = self
        user.add_event_handler("on_user_turn_started", self._on_user_turn_started)
        user.add_event_handler("on_user_turn_stopped", self._on_user_turn_stopped)

    # Pipecat's late copy of the turn. Its three "wait for the user" checks read
    # it; always False, so each of them reaches the checks below instead.
    @property
    def _user_speaking(self) -> bool:
        return False

    @_user_speaking.setter
    def _user_speaking(self, _: bool) -> None:
        pass

    def _turn_pending(self) -> bool:
        controller = self._paired_user_aggregator._user_turn_controller
        return controller._user_turn or not self._turn_written

    def run_requested(self) -> None:
        # That run sees the result, so the one held for Eva to stop is redundant.
        self._run_owed = False
        self._push_context_on_bot_stopped_speaking = False

    async def push_context_frame(self, direction=FrameDirection.DOWNSTREAM):
        if direction == FrameDirection.UPSTREAM:  # upstream is a run request
            self.run_requested()
        await super().push_context_frame(direction)

    async def _maybe_push_context_after_function_result(self):
        self._run_owed = True
        if self._turn_pending():
            logger.debug(
                f"{self}: learner's turn still open, holding the post-tool run"
            )
        else:
            await super()._maybe_push_context_after_function_result()

    async def process_frame(self, frame: Frame, direction: FrameDirection):
        # Eva can stop before a new turn's interruption reaches us: keep it owed.
        if isinstance(frame, BotStoppedSpeakingFrame) and self._turn_pending():
            self._push_context_on_bot_stopped_speaking = False
        await super().process_frame(frame, direction)

    async def _on_user_turn_started(self, aggregator, strategy):
        self._turn_written = False

    async def _on_user_turn_stopped(self, aggregator, strategy, message):
        self._turn_written = True
        # Pipecat's empty-turn reply, if it ran, has already cleared the debt.
        if self._run_owed and not self._turn_pending():
            logger.debug(
                f"{self}: learner's turn closed, running the held post-tool run"
            )
            await super()._maybe_push_context_after_function_result()

The 1.11.0 version differed only in the last method: an empty turn was left to our own "didn't catch that" re-prompt (if self._run_owed and message.content and not self._turn_pending():).

We build the two halves the way LLMContextAggregatorPair does, with our classes:

python
user_aggregator = PostToolUserAggregator(context, params=user_params)
assistant_aggregator = PostToolAssistantAggregator(
    context, params=assistant_params, _paired_user_aggregator=user_aggregator
)

Alternative Solutions

  • #5838: defer the run until UserStoppedSpeakingFrame. It would fix our race. But when the user really is still talking when the result lands, their own end-of-turn inference already sees the result, and the deferred push fires anyway once UserStoppedSpeakingFrame reaches the assistant aggregator. That starts a second LLM run for a result that was already answered. In our check this is the variant of the workaround that never cancels the owed run, and it fails as a double run. Clearing the deferral whenever the user aggregator pushes context would fix it.
  • Run on every result, whatever the turn state. That talks over a user who is still speaking, which is why the check exists.
  • run_llm=False in the tool, then our own LLMRunFrame after a delay. The race is still there, only later. A fixed delay either adds latency to every tool call or is still too short.
  • Run as soon as UserStoppedSpeakingFrame arrives. The run can start before the turn's last words are written to the context, so the LLM answers without them. Our check has a case for this ("result lands while the turn's words are written").

Additional Context

  • Setup. pipecat 1.11.0 when these sessions ran; the workaround now runs on 1.12.0. Python 3.13, Pipecat Cloud, Daily transport. LLMUserAggregator and LLMAssistantAggregator with turn completion (FilterIncompleteUserTurnStrategies). ExternalUserTurnStartStrategy and ExternalUserTurnStopStrategy driven by Soniox endpointing, with Silero VAD only for opening turns. GoogleLLMService (Gemini) and Cartesia TTS.

  • Attachments.

  • What the check does. It runs the workaround and pipecat's own classes side by side, in two layers:

    • end to end: pipecat's turn controller, turn completion and function calling, with a scripted LLM and user, and added delays on the frames that race in production;
    • frame orders: the two aggregators alone, fed turn, tool and speech frames in exact orders, most of them random.

    In every trial, each result that asks for a run must get one within 0.5 s of the moment the turn is closed and written and the bot is silent. The run must never start while the turn is open, and never when another run has already seen the result. On 1.12.0 all 166 cases pass. On 1.11.0 a larger run of 470 cases passed, and 1,000 more random frame orders showed no problem caused by the workaround. Every deliberately broken variant of the workaround fails the check.

Would you be willing to help implement this feature?

  • Yes, I'd like to contribute
  • No, I'm just suggesting