Hi everyone i have a simple usecase of pausing my ...
# agents
g
Hi everyone i have a simple usecase of pausing my agent SST / LLM / TTS processing till my function call is over I have tried to use session.input.set_audio_enabled(False) session.output.set_audio_enabled(False) and it is not working still the STT happens, am i doing anything wrong ?
Copy code
import logging
import asyncio

from dotenv import load_dotenv
from livekit.agents import (
    Agent,
    AgentSession,
    JobContext,RunContext,
    JobProcess,
    MetricsCollectedEvent,
    RoomInputOptions,
    WorkerOptions,
    cli,
    metrics,
    function_tool,
    AudioConfig,
    BackgroundAudioPlayer
)
from livekit.plugins import noise_cancellation, silero, openai, deepgram
from livekit.plugins.turn_detector.multilingual import MultilingualModel

logger = logging.getLogger("agent")

load_dotenv(".env.local")

def pause_audio(session: AgentSession):
    session.input.set_audio_enabled(False)
    session.output.set_audio_enabled(False)
    logger.info("Audio disabled")

def resume_audio(session: AgentSession):
    session.input.set_audio_enabled(True)
    session.output.set_audio_enabled(True)
    logger.info("Audio enabled")

class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""You are a helpful voice AI assistant. who will immediately call the open gate function for main entrance """,
        )

    @function_tool
    async def open_gate(self, action: str, gate_id: str, ctx: RunContext):
        await ctx.wait_for_playout()
        
        """Internal helper to perform gate control actions on a gate."""
        logger.info(f"{action.title()}ing gate: {gate_id}")

        # print all functions present in the context
        logger.info(f"Functions present in the context: {dir(ctx)}")
        await self.session.say("Okay executing the task",allow_interruptions=False)

        # all session options
        logger.info(f"Session options: {dir(self.session)}")

        pause_audio(self.session)

        # sleep for 10 seconds
        await asyncio.sleep(20)


        resume_audio(self.session)
        logger.info("Audio enabled after 10 seconds")
        # TODO: Insert actual gate control logic here.
        return f"Gate {gate_id} {action}ed successfully"

def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load()


async def entrypoint(ctx: JobContext):
    # Logging setup
    # Add any other context you want in all log entries here
    ctx.log_context_fields = {
        "room": ctx.room.name,
    }

    # Set up a voice AI pipeline using OpenAI, Cartesia, AssemblyAI, and the LiveKit turn detector
    session = AgentSession(
        stt=openai.STT(model= "gpt-4o-transcribe"),
        llm=openai.LLM(model="gpt-4.1"),
        tts=deepgram.TTS(model="aura-2-thalia-en"),
        turn_detection=MultilingualModel(),
        vad=ctx.proc.userdata["vad"],
        allow_interruptions=True,
        user_away_timeout=30,
    )

    # To use a realtime model instead of a voice pipeline, use the following session setup instead.
    # (Note: This is for the OpenAI Realtime API. For other providers, see https://docs.livekit.io/agents/models/realtime/))
    # 1. Install livekit-agents[openai]
    # 2. Set OPENAI_API_KEY in .env.local
    # 3. Add `from livekit.plugins import openai` to the top of this file
    # 4. Use the following session setup instead of the version above
    # session = AgentSession(
    #     llm=openai.realtime.RealtimeModel(voice="marin")
    # )

    # Metrics collection, to measure pipeline performance
    # For more information, see https://docs.livekit.io/agents/build/metrics/
    usage_collector = metrics.UsageCollector()

    @session.on("metrics_collected")
    def _on_metrics_collected(ev: MetricsCollectedEvent):
        metrics.log_metrics(ev.metrics)
        usage_collector.collect(ev.metrics)

    async def log_usage():
        summary = usage_collector.get_summary()
        logger.info(f"Usage: {summary}")

    ctx.add_shutdown_callback(log_usage)

    # # Add a virtual avatar to the session, if desired
    # # For other providers, see https://docs.livekit.io/agents/models/avatar/
    # avatar = hedra.AvatarSession(
    #   avatar_id="...",  # See https://docs.livekit.io/agents/models/avatar/plugins/hedra
    # )
    # # Start the avatar and wait for it to join
    # await avatar.start(session, room=ctx.room)

    # Start the session, which initializes the voice pipeline and warms up the models
    await session.start(
        agent=Assistant(),
        room=ctx.room,
        room_input_options=RoomInputOptions(
            # For telephony applications, use `BVCTelephony` for best results
            noise_cancellation=noise_cancellation.BVC(),
        ),
    )

    await session.generate_reply(
        instructions="Greet the user warmly and ask how you can help."
    )

    # Join the room and connect to the user
    await ctx.connect()


if __name__ == "__main__":
    cli.run_app(WorkerOptions(agent_name="macbook-local", entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))
cc: @refined-appointment-81829
l
Rather than stop the STT,
session.input.set_audio_enabled(False)
will stop audio frames being sent to the room, effectively pausing your pipeline and 'stopping processing' which I believe is your end goal?. I wouldn't recommend stopping STT entirely as it's not really designed to work that way and there are not any public APIs to easily do this.
g
Understood @lively-winter-88668 the issue I’m facing is that when I invoke a function example: create a ticket (which can take around 10–20 seconds to complete), the user might say something like “hi” or “hello” during that time. Those messages are still being transcribed and sent to the LLM. As a result, once the ticket creation is done, instead of responding with “I’ve created the ticket,” the agent restarts the conversation as if it’s a new interaction. I’d like to know if there’s a way to pause the agent — specifically to stop both speech-to-text (STT) and LLM processing — until the function call completes. Could you please guide me on how to implement that?
r
You could hook the STT node and drop the input until your processor is done. This is not exactly what you need but in this case we drop the input until the STT finds the wake word: https://github.com/livekit-examples/python-agents-examples/blob/main/home_assistant/homeautomation.py#L77
👀 1
g
okay @refined-appointment-81829 will check the implementation, thanks for sharing
@refined-appointment-81829 I did a implementation based on your suggestion and it is working fine thanks for the help 🙌
🎉 1