great-beard-25624
10/29/2025, 10:35 AMimport 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-81829lively-winter-88668
10/29/2025, 11:32 AMsession.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.great-beard-25624
10/29/2025, 12:10 PMrefined-appointment-81829
10/29/2025, 2:10 PMgreat-beard-25624
10/30/2025, 3:39 AMgreat-beard-25624
10/30/2025, 5:22 AM