<#C088ZNU7QQ5|ask-ai> import os from Agents.compl...
# ask-ai
i
#ask-ai import os from Agents.complete_restaurant_agent import CompleteRestaurantAgent from Common.DataPacket.data_models import CompleteMenu, InformationPacket from Common.restaurant_logger import logger from livekit.agents import ( Agent, AgentSession, AutoSubscribe, JobContext, MetricsCollectedEvent, RoomInputOptions, RunContext, WorkerOptions, cli, function_tool, metrics, ) from livekit.plugins.noise_cancellation import BVC from ServiceManager.DataPacketBuilder import InformationPacketInitializer from ServiceManager.DataPacketBuilder.data_models_builder import DataModelsBuilder from Session import get_google_realtime_session, get_tts_llm_stt_session from livekit.agents import ( NOT_GIVEN, Agent, AgentFalseInterruptionEvent, AgentSession, JobContext, JobProcess, MetricsCollectedEvent, RoomInputOptions, RunContext, WorkerOptions, cli, metrics, ) # Toggle between single-agent and multi-agent architecture # Set to True to use new multi-agent system, False for legacy single agent USE_MULTI_AGENT = False _# os.getenv("USE_MULTI_AGENT", "true").lower() == "false"_ class Pipeline: def __init__(self): self.data_models_builder = DataModelsBuilder() self.usage_collector = metrics.UsageCollector() self.information_packet_initializer = InformationPacketInitializer() logger.info(f"Pipeline initialized") # Global context: information packet shared across all participants self.information_packet = None self._information_packet_initialized = False async def prewarm(self, ctx: JobContext): """ Prewarm function called by LiveKit worker before processing any jobs. Initializes global context (restaurant info + menu) once. """ logger.info("🔥 Prewarming: Initializing global context...") await self.initialize_global_context() logger.info("✅ Prewarm complete: Global context ready") async def initialize_global_context(self): """ Initialize global context with restaurant information and menu. This is called once at startup and shared across all participants. """ if self._information_packet_initialized and self.information_packet: logger.info("✅ Global context already initialized, reusing cached data") return self.information_packet logger.info("🔄 Initializing global context (restaurant info + menu)...") try: self.information_packet = await self.information_packet_initializer.get_all_information() self._information_packet_initialized = True # Log what was loaded if self.information_packet: r_info = self.information_packet.restaurant_info menu = self.information_packet.complete_menu logger.info( f"✅ Global context initialized:\n" f" Restaurant: {r_info.name}\n" f" Menu Categories: {len(menu.menu_categories)}\n" f" Menu Items: {len(menu.menu_items)}" ) return self.information_packet except Exception as e: logger.error(f"❌ Failed to initialize global context: {e}") self.information_packet = None self._information_packet_initialized = False return None async def entrypoint(self, ctx: JobContext): @ctx.room.on("participant_connected") def on_participant_connected(participant): if participant.identity: # The participant's identity might contain the phone number depending on how your SIP integration is configured. logger.info(f"Participant connected: {participant.identity}") # You might need to parse the identity if it contains other information in addition to the phone number. if participant.metadata: # Custom metadata passed during the SIP connection can also contain the phone number or other call details. logger.info(f"Participant metadata: {participant.metadata}") @ctx.room.on("participant_attributes_changed") def on_participant_attributes_changed(changed_attrs: dict[str, str], participant): logger.info(f"Participant {participant.identity} updated attributes: {changed_attrs}") logger.info(f"Current attributes: {participant.attributes}") information_packet = await self.initialize_global_context() if not information_packet: logger.error("Global context not available, cannot start agent") return # Now start the session and connect to the room logger.info(f"Starting call center agent for room: {ctx.room.name}") await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY) # Wait for the participant to join participant = await ctx.wait_for_participant() logger.info(f"Participant joined: {participant.identity}") # Build data packet for this participant data_packet = await self.data_models_builder.build_data_packet(participant=participant, information_packet=information_packet) # Create session with multi-agent flag session = get_google_realtime_session(datapacket=data_packet, use_multi_agent=USE_MULTI_AGENT) _# @session.on("metrics_collected")_ _# async def _on_metrics_collected(ev: MetricsCollectedEvent):_ _# metrics.log_metrics(ev.metrics)_ _# self.usage_collector.collect(ev.metrics)_ try: logger.info("Starting SINGLE-AGENT system") await session.start( agent=CompleteRestaurantAgent(chat_ctx=None, datapacket=data_packet), room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=BVC(), ), ) # Greeting instruction after the session has started logger.info("Call center agent session started and ready") await session.generate_reply( instructions="Good evening! Welcome to Village Restaurant. How may I help you today?" ) except Exception as e: logger.error(f"Failed to start agent session with realtime model: {e}") logger.info("Attempting to restart with traditional STT/LLM/TTS pipeline...") try: fallback_session = get_tts_llm_stt_session() await fallback_session.start(agent=CompleteRestaurantAgent(), room=ctx.room) logger.info("Village call center agent session started with traditional pipeline") except Exception as fallback_error: logger.error(f"Failed to start with traditional pipeline: {fallback_error}") # Final fallback with minimal configuration logger.info("Attempting final fallback with minimal realtime configuration...") Do i have to use the given lines # Now start the session and connect to the room logger.info(f"Starting call center agent for room: {ctx.room.name}") await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY) # Wait for the participant to join participant = await ctx.wait_for_participant() logger.info(f"Participant joined: {participant.identity}") before initializing session or starting session or after initializing session because my greeting does not work
t
Thanks for reaching out, Maaz. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking whether the connect/wait-for-participant lines must run before/after initializing/starting the session because your greeting isn't playing. Short answer: yes — and the correct sequence plus a couple of checks will fix most greeting issues. What to run and in what order 1. Initialize the session object (create
session = get_google_realtime_session(...)
). 2. Connect to the room:
await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
. 3. Wait for participant:
participant = await ctx.wait_for_participant()
. 4. Start the session:
await session.start(...)
. 5. Send the greeting:
await session.generate_reply(...)
(or use
await session.say(...)
for direct TTS). Why:
ctx.connect()
and
wait_for_participant()
must occur before
session.start()
so the agent joins a ready room and has a participant to address.
generate_reply()
must be awaited and called after
session.start()
so the session and audio pipeline are ready to play the greeting. If your greeting still doesn’t play, check these common causes • Use
session.say()
for realtime sessions if
generate_reply()
doesn't trigger speech (realtime LLMs sometimes expect live input;
session.say()
plays TTS directly). • Confirm
await session.start(...)
completed without exceptions (your logs should show success). • Ensure the agent token/connection allows publishing audio (publish audio permissions). • Add a small delay or readiness check after
session.start()
if the realtime model needs extra time before producing audio. If you want, paste the exact log lines around
session.start()
and your
generate_reply()
call and I’ll help pinpoint which of the above is happening. Sources: Job lifecycle | LiveKit docs | Voice AI quickstart | LiveKit docs | Agents v0.x migration guide - Node.js | LiveKit Docs | Agent speech and audio | LiveKit docs | Connecting to LiveKit | LiveKit docs
i
#ask-ai why multi agents cannot transfer call to another agent for my scenario it always appears that we are transferring to another agent but it never happens
t
You're seeing the transfer appear to start but never complete — here are the most likely causes and the specific checks to run. Key distinction (most common root cause) • Agent handoff != SIP call transfer. Returning a new agent or using an LLM handoff hands control to a different agent inside LiveKit but does not forward the underlying PSTN/SIP call. To move the phone call off the current room you must call the SIP transfer API (
TransferSIPParticipant
) which issues a SIP REFER to your trunk. What to verify (step-by-step) 1. SIP REFER enabled on your provider ◦ Ensure your SIP trunk (Twilio, Telnyx, etc.) allows SIP REFER / PSTN transfer. If REFER is disabled the transfer request will be ignored. 1. You are calling the transfer API (not just doing an agent handoff) ◦ Use
job_ctx.api.sip.transfer_sip_participant(...)
/
TransferSIPParticipantRequest
with the target number. Agent handoffs alone won’t move the call. 1. Dispatch / agent routing configuration ◦ If transferring to another LiveKit agent endpoint/phone, ensure the destination agent has
agent_name
set in its entrypoint and a matching dispatch rule mapping the number to that agent. 1. Caller ID and trunk restrictions ◦ Some trunks reject transfers if caller ID is missing or invalid. Use the `sip_number`/caller fields when creating/transfering participants and verify your provider allows the caller ID you send. 1. Check logs and SIP response codes ◦ Look for SIP errors (408, 503, or 4xx/5xx) or silent rejections in your logs — they show why the remote endpoint didn’t accept the REFER or invite. 1. Race conditions / timing ◦ Ensure the transfer request runs after the room/participant state is stable. Add logging around the transfer call and confirm
transfer_sip_participant
returns success. Concrete example (transfer API)
Copy code
await job_ctx.api.sip.transfer_sip_participant(
    api.TransferSIPParticipantRequest(
        room_name=job_ctx.room.name,
        participant_identity=participant_identity,
        transfer_to=f"tel:+15105550123",
    )
)
Next diagnostic steps I can help with • Paste the transfer-related logs (including any SIP response codes) and the code you use to initiate the transfer. • Tell me which SIP provider you use (Twilio, Telnyx, etc.) so I can point to provider-specific settings to check. Tell me which of the above you'd like to start with and share the logs/code if available. Sources: SIP troubleshooting guide | LiveKit docs | Call forwarding | LiveKit docs | Agents telephony integration | LiveKit Docs | SIP APIs | LiveKit docs | Agent dispatch | LiveKit docs