Hey, in this example (<https://github.com/livekit/...
# agents
r
Hey, in this example (https://github.com/livekit/agents/blob/main/examples/voice_agents/fast-preresponse.py), how can I make it so that tool calls by the main LLM get executed while the fast pre_response is still being spoken? In the example, tools are only executed after the fast_llm_reply has been spoken. My tools take some time so I’d like to start them as early as possible.
j
you can remove
await fast_llm_fut
in the example to run the main LLM in parallel, or call
session.generate_reply
in the function call instead
r
Even when doing this it seems tools only get executed after the fast llm finishes speaking. In this file, https://github.com/livekit/agents/blob/main/livekit-agents/livekit/agents/voice/agent_activity.py, tool execution is blocked until play finishes. The the following comment in that file: “start to execute tools (only after play())”
j
no, tool execution starts before audio playout finished
r
I don't think so, here is an example. In the screenshot you can see nearly 20 seconds between the transcript being generated and the function call (_fast_llm is running during this time). I am looking to have the functions execute before the _fast_llm finishes speaking.
Copy code
import asyncio
import logging
from collections.abc import AsyncIterable
import random
from typing import Annotated

from dotenv import load_dotenv

from livekit.agents import (
    Agent,
    AgentSession,
    JobContext,
    WorkerOptions,
    cli,
    llm,
)
from livekit.agents.llm.chat_context import ChatContext, ChatMessage
from livekit.plugins import deepgram, groq, openai, silero
from livekit.agents.llm import function_tool
from pydantic import Field

logger = logging.getLogger("pre-reseponse-agent")

load_dotenv()


class PreResponseAgent(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant",
            llm=groq.LLM(model="llama-3.3-70b-versatile"),
        )
        self._fast_llm = groq.LLM(model="llama-3.1-8b-instant")
        self._fast_llm_prompt = llm.ChatMessage(
            role="system",
            content=[
                "Tell the user a short poem about the weather, using simple and natural language.",
            ],
        )
        
    async def on_enter(self) -> None:
        self.session.generate_reply()
        
    @function_tool
    async def get_number(
        self,
        value: Annotated[int | None, Field(description="The number value")],
    ) -> str:
        """
        Called when the user wants to get a number value, None if user want a random value
        """
        logger.info(f"Get number called with value: {value}")
        return f"The number value is 5."

    async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage):
        # Create a short "silence filler" response to quickly acknowledge the user's input
        fast_llm_ctx = turn_ctx.copy(
            exclude_instructions=True, exclude_function_call=True
        ).truncate(max_items=3)
        fast_llm_ctx.items.insert(0, self._fast_llm_prompt)
        fast_llm_ctx.items.append(new_message)

        #  Intentionally not awaiting SpeechHandle to allow the main response generation to
        # run concurrently
        self.session.say(
             self._fast_llm.chat(chat_ctx=fast_llm_ctx).to_str_iterable(),
             add_to_chat_ctx=False,
         )



async def entrypoint(ctx: JobContext):
    session = AgentSession(
        stt=deepgram.STT(),
        tts=openai.TTS(),
        vad=silero.VAD.load(),
    )
    await session.start(PreResponseAgent(), room=ctx.room)


if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
j
I see your point, the tool hast to wait for the associated speech started, the fast llm is another speech in this case
You can use say or generate reply inside the tool call for your use case