agents icon indicating copy to clipboard operation
agents copied to clipboard

A speech ends on "listening" while a deferred tool reply is still owed

Open zek opened this issue 4 weeks ago • 4 comments

Bug Description

A tool that calls ctx.update() and finishes later gets its reply in a deferred task. The executor holds that reply in _pending_updates and waits for the agent to go idle before it speaks (tool_executor.py#L568-L590).

If another speech plays in that window, for example the reply to a second user message, that speech ends on listening (agent_activity.py#L3176-L3182). _background_speeches does not include the pending reply, so the agent looks idle. The tool reply then plays after the listening edge.

A client that reads listening as the end of the turn ends it before the tool answer. The user-away timer also arms while the answer is still owed. An inline tool reply that waits behind another speech shows the same listening edge on realtime models.

This is close to https://github.com/livekit/agents/issues/6904, which https://github.com/livekit/agents/pull/6937 fixed for a tool that is still running. Here the tool has finished, but its reply is not spoken yet.

Expected Behavior

While a tool reply is owed, a speech ends on thinking, not listening. The agent goes to listening after the owed reply plays, or when the reply is dropped.

Reproduction Steps

The script below runs a text-only AgentSession with a scripted LLM. No credentials or network are needed.

  1. The user asks for the weather. The LLM calls lookup_weather, which calls ctx.update() and waits.
  2. The user sends a second message. The tool finishes while the second reply is generated.
  3. The script prints the agent state edges.

repro.py:

# /// script
# requires-python = ">=3.10"
# dependencies = ["livekit-agents"]
# ///
"""A speech ends on `listening` while a deferred tool reply is still owed.

The script runs a text-only AgentSession with a scripted LLM. The first turn calls a
tool that sends `ctx.update()` and finishes later. The user sends a second message.
The tool finishes while the second reply is generated, so the executor holds the tool
reply until the agent is idle. The script records the agent state edges.
"""

from __future__ import annotations

import asyncio
import platform
import sys
from importlib.metadata import version
from typing import Any

from livekit.agents import Agent, AgentSession, RunContext, function_tool, llm
from livekit.agents.types import DEFAULT_API_CONNECT_OPTIONS, APIConnectOptions

TOOL_ANSWER = "It is sunny."


class ScriptedLLM(llm.LLM):
    def __init__(self, agent: WeatherAgent) -> None:
        super().__init__()
        self.agent = agent

    def chat(
        self,
        *,
        chat_ctx: llm.ChatContext,
        tools: list[llm.Tool] | None = None,
        conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
        **kwargs: Any,
    ) -> llm.LLMStream:
        return ScriptedStream(
            self, chat_ctx=chat_ctx, tools=tools or [], conn_options=conn_options
        )


class ScriptedStream(llm.LLMStream):
    async def _run(self) -> None:
        last = self._chat_ctx.items[-1]
        if last.type == "message" and last.role == "user" and "weather" in last.text_content:
            call = llm.FunctionToolCall(name="lookup_weather", arguments="{}", call_id="call_1")
            delta = llm.ChoiceDelta(role="assistant", tool_calls=[call])
        elif last.type == "message" and last.role == "user":
            # the tool finishes while this reply is generated
            self._llm.agent.finish_lookup.set()
            await asyncio.sleep(0.3)
            delta = llm.ChoiceDelta(role="assistant", content="Once upon a time.")
        elif any(
            item.type == "function_call_output" and item.output == "sunny"
            for item in self._chat_ctx.items
        ):
            delta = llm.ChoiceDelta(role="assistant", content=TOOL_ANSWER)
        else:
            delta = llm.ChoiceDelta(role="assistant", content="I am checking the weather.")
        self._event_ch.send_nowait(llm.ChatChunk(id="chunk", delta=delta))


class WeatherAgent(Agent):
    def __init__(self) -> None:
        super().__init__(instructions="Answer briefly.")
        self.finish_lookup = asyncio.Event()

    @function_tool
    async def lookup_weather(self, context: RunContext) -> str:
        """Look up the weather."""
        await context.update("checking the weather")
        await self.finish_lookup.wait()
        return "sunny"


async def run_session() -> list[str]:
    agent = WeatherAgent()
    session = AgentSession(llm=ScriptedLLM(agent))
    edges: list[str] = []
    answered = asyncio.Event()

    @session.on("agent_state_changed")
    def _on_state(ev: Any) -> None:
        edges.append(ev.new_state)

    @session.on("conversation_item_added")
    def _on_item(ev: Any) -> None:
        if getattr(ev.item, "role", None) == "assistant" and ev.item.text_content == TOOL_ANSWER:
            edges.append("<tool answer>")
            answered.set()

    await session.start(agent)
    await session.run(user_input="What is the weather?")
    edges.append("<second message>")
    await session.run(user_input="Tell me a story first.")
    await asyncio.wait_for(answered.wait(), timeout=10)
    await asyncio.sleep(0.2)
    await session.aclose()
    return edges


def main() -> int:
    print(f"livekit-agents {version('livekit-agents')}, Python {platform.python_version()}")
    edges = asyncio.run(run_session())
    print("agent state edges:", " ".join(edges))
    start = edges.index("<second message>")
    end = edges.index("<tool answer>")
    window = edges[start:end]
    if "listening" in window:
        print("PROBLEM PRESENT: the agent state reached listening before the tool answer")
        return 1
    print("PROBLEM ABSENT: the agent state stayed off listening until the tool answer")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Run it:

uv run --python 3.12 --with livekit-agents==1.8.10 repro.py

Output:

livekit-agents 1.8.10, Python 3.12.12
agent state edges: listening thinking speaking listening <second message> thinking speaking listening thinking speaking <tool answer> listening
PROBLEM PRESENT: the agent state reached listening before the tool answer

After <second message>, the edge sequence is speaking listening thinking speaking. The listening edge comes before the tool answer.

Operating System

macOS 26.7.1

Models Used

Scripted llm.LLM in the script. Also seen with the OpenAI realtime model.

Package Versions

livekit-agents==1.8.10

Proposed Solution

Count an owed tool reply as busy where a speech ends: the executor's _pending_updates, and speech tasks that are not done yet. When the last owed reply finishes or is dropped, publish listening.

zek avatar Nov 03 '26 21:11 zek

I'd like to take this on. I'll start from the provided text-only reproduction, trace how pending deferred tool replies interact with AgentActivity state transitions, and work on a focused fix with a regression test.

The test will verify that the agent stays busy while a deferred tool reply is still owed, and returns to listening once the reply has been delivered or dropped.

I'll link the PR here when it's ready.

Epsilon006 avatar Nov 04 '26 02:11 Epsilon006

I ran your repro unchanged (scripted LLM, no network) against our local checkout of this line (based on 1.8.x main): same edges, speaking listening right after the second message with the tool answer still owed.

This is the same class we hit in #7898 (closed by longcw): treating a speech-level signal as proof the turn is semantically complete. There the concession was that a final only covers the turn when no speech follows it; here the mirror image: listening should mean "nothing playing and nothing owed", and a reply sitting in the executor's _pending_updates is the "owed" part. Your proposed fix direction matches that invariant, so +1 from our side.

@Epsilon006 for the regression test, two things beyond the state edges:

  1. The user-away timer arms in the same window (mentioned in the issue); an assertion there is the user-visible cost of this bug.
  2. The realtime variant (inline tool reply waiting behind another speech) goes through a different path than text-only; the same listening edge shape shows up there per your OpenAI realtime note, so the same assertion on that path is worth having.

iamdgarcia avatar Nov 05 '26 14:11 iamdgarcia

Thanks for reproducing this and confirming the invariant!

I’ve opened #8379 with the fix. The regression tests cover both the user-away timer behavior and the realtime auto-tool-reply path, including overlapping pending replies.

Appreciate the additional validation and suggestions!

Epsilon006 avatar Nov 05 '26 14:11 Epsilon006

Thanks for the fix in #8459. The original reproduction passes on livekit-agents==1.8.12. Two cases still end a speech on listening while more speech is owed.

  1. A tool that called ctx.update() is still running. The update reply ends on listening, then the tool answer plays. A client that reads listening as the end of the turn stops before the answer, and the user-away timer arms while the tool runs.
  2. A say() is queued behind another. The first speech ends on listening although the second is already in the queue.

_has_followup_work says it reports "whether another speech is already committed to follow the current one". It checks _background_speeches and _pending_updates, but not a running tool after its first update, nor _speech_q.

Expected: both cases stay on thinking until the last owed speech plays, as #6937 does for a tool that has not called ctx.update() yet.

The script runs a text-only AgentSession with a scripted LLM. No credentials or network are needed.

repro.py
# /// script
# requires-python = ">=3.10"
# dependencies = ["livekit-agents==1.8.12"]
# ///
"""Agent state edges for owed replies, with a scripted LLM and no network."""

from __future__ import annotations

import asyncio
import platform
import sys
from importlib.metadata import version
from typing import Any

from livekit.agents import Agent, AgentSession, RunContext, function_tool, llm
from livekit.agents.types import DEFAULT_API_CONNECT_OPTIONS, APIConnectOptions

TOOL_ANSWER = "It is sunny."
TIMEOUT = 10


class ScriptedLLM(llm.LLM):
    def chat(
        self,
        *,
        chat_ctx: llm.ChatContext,
        tools: list[llm.Tool] | None = None,
        conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
        **kwargs: Any,
    ) -> llm.LLMStream:
        return ScriptedStream(self, chat_ctx=chat_ctx, tools=tools or [], conn_options=conn_options)


class ScriptedStream(llm.LLMStream):
    async def _run(self) -> None:
        last = self._chat_ctx.items[-1]
        if last.type == "message" and last.role == "user" and "weather" in last.text_content:
            call = llm.FunctionToolCall(name="lookup_weather", arguments="{}", call_id="call_1")
            delta = llm.ChoiceDelta(role="assistant", content="I am checking.", tool_calls=[call])
        elif any(i.type == "function_call_output" and i.output == "sunny" for i in self._chat_ctx.items):
            delta = llm.ChoiceDelta(role="assistant", content=TOOL_ANSWER)
        else:
            delta = llm.ChoiceDelta(role="assistant", content="Okay.")
        self._event_ch.send_nowait(llm.ChatChunk(id="chunk", delta=delta))


class WeatherAgent(Agent):
    def __init__(self) -> None:
        super().__init__(instructions="Answer briefly.")
        self.finish = asyncio.Event()
        self.updated = asyncio.Event()

    @function_tool
    async def lookup_weather(self, context: RunContext) -> str:
        """Look up the weather."""
        await context.update("checking the weather")
        self.updated.set()
        await self.finish.wait()
        return "sunny"


class Recorder:
    def __init__(self, session: AgentSession) -> None:
        self.edges: list[str] = []
        self.answered = asyncio.Event()
        session.on("agent_state_changed", lambda ev: self.edges.append(ev.new_state))
        session.on("conversation_item_added", self._item)

    def _item(self, ev: Any) -> None:
        if getattr(ev.item, "role", None) == "assistant" and ev.item.text_content == TOOL_ANSWER:
            self.edges.append("<tool answer>")
            self.answered.set()

    def mark(self, label: str) -> None:
        self.edges.append(f"<{label}>")


async def settle() -> None:
    for _ in range(20):
        await asyncio.sleep(0.05)


async def started(agent: Agent) -> tuple[AgentSession, Recorder]:
    session = AgentSession(llm=ScriptedLLM())
    recorder = Recorder(session)
    await session.start(agent)
    recorder.edges.clear()
    return session, recorder


async def released_tool() -> tuple[list[str], bool]:
    """The tool sent ctx.update() and is still running. Its answer is still owed."""
    agent = WeatherAgent()
    session, rec = await started(agent)
    session.generate_reply(user_input="What is the weather?")
    await asyncio.wait_for(agent.updated.wait(), TIMEOUT)
    await settle()
    rec.mark("tool still running")
    agent.finish.set()
    await asyncio.wait_for(rec.answered.wait(), TIMEOUT)
    await settle()
    await session.aclose()
    edges = rec.edges
    return edges, "listening" not in edges[: edges.index("<tool answer>")]


async def queued_says() -> tuple[list[str], bool]:
    """A second say() is queued behind the first. The agent stays busy between them."""
    session, rec = await started(Agent(instructions="Answer briefly."))
    first = session.say("Hello.")
    second = session.say("Again.")
    await asyncio.wait_for(asyncio.gather(first.wait_for_playout(), second.wait_for_playout()), TIMEOUT)
    await settle()
    await session.aclose()
    return rec.edges, "listening" not in rec.edges[:-1]


CASES = [released_tool, queued_says]


def main() -> int:
    print(f"livekit-agents {version('livekit-agents')}, Python {platform.python_version()}")
    failed = 0
    for case in CASES:
        edges, ok = asyncio.run(case())
        failed += not ok
        print(f"{'PASS' if ok else 'FAIL'} {case.__name__}: {' '.join(edges)}")
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())
$ uv run repro.py
livekit-agents 1.8.12, Python 3.12.12
FAIL released_tool: thinking speaking thinking speaking listening <tool still running> thinking speaking <tool answer> listening
FAIL queued_says: speaking listening speaking listening

For case 1, the ctx.update() docstring says the first update releases control to the LLM. If listening there is intended, which signal should a client use to know that a tool answer is still owed?

zek avatar Nov 18 '26 17:11 zek