m
hi
t
Thanks for reaching out, aigentzi. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi — how can I help you today? What are you trying to do with LiveKit (setting up a room, connecting a client, SDK errors, billing, or something else)? If you have an error message or a room/project ID, please share it.
m
can you review and edn bcak a better version for an ai english teacher onliovekit cloud with inference ; import asyncio import json import logging import os import traceback from livekit.agents import AgentServer, JobContext, room_io, cli, stt from livekit.agents.voice import AgentSession, Agent from livekit.plugins import silero # Set up detailed logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger("en-agent-01") server = AgentServer() # Model configuration (LiveKit Inference identifiers) STT_PRIMARY = "livekit/deepgram/nova-3" STT_SECONDARY = "livekit/assemblyai/universal-streaming:en" LLM_MODEL = "livekit/openai/gpt-4o-mini" TTS_MODEL = "livekit/cartesia/sonic-3" COMMIT_SHA = os.getenv("COMMIT_SHA", "dev-local") AGENT_TOPIC = "agent_control" @server.rtc_session(_agent_name_="en-agent-01") async def *entry*(_ctx_: JobContext): logger.info("šŸ”– Agent version commit=%s", COMMIT_SHA) # Connect to room with auto-subscribe enabled (audio focus) await ctx.connect(_auto_subscribe_=True) logger.info(f"āœ… Connected to room: {ctx.room.name}") # Track subscription logging @_ctx_.room.on("track_subscribed") def *_on_track_subscribed*(track, pub, participant): logger.info( "āœ… track_subscribed kind=%s name=%s from=%s sid=%s", getattr(track, "kind", None), getattr(pub, "name", None), participant.identity, participant.sid ) @_ctx_.room.on("track_published") def *_on_track_published*(pub, participant): logger.info( "šŸ“¢ track_published kind=%s name=%s from=%s sid=%s", pub.kind, pub.name, participant.identity, participant.sid ) @_ctx_.room.on("track_unsubscribed") def *_on_track_unsubscribed*(track, pub, participant): logger.info( "āŒ track_unsubscribed kind=%s from=%s", getattr(track, "kind", None), participant.identity ) # Wait for student to join student_identity = None # Check if student already in room for p in ctx.room.remote_participants.values(): if not p.identity.startswith('agent-'): student_identity = p.identity logger.info(f"šŸ‘¤ Student already in room: {student_identity}") break # If not, wait for them to join if not student_identity: logger.info("ā³ Waiting for student to join...") student_joined = asyncio.Event() @_ctx_.room.on("participant_connected") def *_on_participant_connected*(participant): nonlocal student_identity if not participant.identity.startswith('agent-'): student_identity = participant.identity logger.info(f"šŸ‘¤ Student joined: {student_identity}") student_joined.set() _try_: await asyncio.wait_for(student_joined.wait(), timeout=30.0) except asyncio.TimeoutError: logger.error("ā±ļø Timeout waiting for student to join") return logger.info(f"šŸŽÆ Student identity confirmed: {student_identity}") # Create VAD with sensitive settings; fallback gracefully if unavailable vad = None turn_mode = "vad" _try_: vad = silero.VAD.load( _min_speech_duration_=0.05, _min_silence_duration_=0.5, _activation_threshold_=0.2, _padding_duration_=0.1 ) logger.info("āœ… Silero VAD loaded") except Exception as exc: logger.warning("āš ļø Silero VAD load failed, continuing without VAD: %s", exc) turn_mode = None # Create agent session session = AgentSession( stt=stt.FallbackAdapter([STT_PRIMARY, STT_SECONDARY]), llm=LLM_MODEL, tts=TTS_MODEL, vad=vad, _turn_detection_=turn_mode, _user_away_timeout_=60.0, # avoid immediate away; wait up to 60s of silence ) # Create agent with instructions agent = Agent( instructions="You are a friendly English teacher. Keep replies short and conversational." ) # Helper to publish data messages async def *publish_json*(_payload_: dict): _try_: await ctx.room.local_participant.publish_data( json.dumps(payload).encode(), reliable=True, _destination_identities_=[student_identity] if student_identity else None, topic=payload.get("topic", AGENT_TOPIC) ) logger.info(f"šŸ“¤ Sent: {payload.get('event')}") except Exception as e: logger.exception(f"Failed to publish data: {e}") # Session event listeners away_prompt_sent = False @session.on("user_state_changed") def *_on_user_state*(ev): nonlocal away_prompt_sent logger.info(f"šŸŽ¤ User state: {ev.new_state}") if ev.new_state == "speaking": away_prompt_sent = False logger.info("šŸŽ¤ USER STARTED SPEAKING") elif ev.new_state == "listening": logger.info("šŸ”‡ USER STOPPED SPEAKING") elif ev.new_state == "away" and not away_prompt_sent: away_prompt_sent = True asyncio.create_task(session.say("Are you still there? I can continue when you are ready.", _allow_interruptions_=True)) @session.on("user_input_transcribed") def *_on_transcribed*(ev): transcript = getattr(ev, "transcript", None) is_final = getattr(ev, "is_final", False) if transcript: logger.info(f"šŸ“ Transcribed: '{transcript}' (final={is_final})") @session.on("conversation_item_added") def *_on_history*(ev): logger.info(f"šŸ’¬ {ev.item.role}: {ev.item.text_content}") # Start session with audio enabled, text disabled for testing room_options = room_io.RoomOptions( _audio_input_=True, _audio_output_=True, _text_input_=False ) async def *start_with_retry*(): for attempt in range(2): _try_: await session.start( room=ctx.room, agent=agent, _room_options_=room_options ) logger.info("šŸš€ Agent session started successfully") return True except Exception as exc: logger.exception("āŒ session.start failed (attempt %s): %s", attempt + 1, exc) if attempt == 0: await asyncio.sleep(1.0) return False started = await start_with_retry() if not started: logger.error("āŒ Session failed to start after retries; notifying client and exiting") if student_identity: await publish_json({ "topic": AGENT_TOPIC, "event": "agent_error", "detail": "session_start_failed", }) return # Send greeting _try_: # Share agent version info with the client if student_identity: await publish_json({ "topic": AGENT_TOPIC, "event": "agent_version", "commit": COMMIT_SHA, }) await session.say( "Hello! I'm your English teacher. Let's get started.", _allow_interruptions_=True ) logger.info("šŸ’¬ Greeting spoken") # Notify client if student_identity: await publish_json({ "topic": AGENT_TOPIC, "event": "agent_greeting_completed", "listen_window_ms": 20000 }) # Send ping await asyncio.sleep(0.5) await ctx.room.local_participant.publish_data( b"agent_ping_after_greeting", reliable=True ) logger.info("šŸ“¤ Sent ping after greeting") except Exception as e: logger.error(f"āŒ TTS failed: {e}") logger.error(traceback.format_exc()) # Keep alive until disconnect disconnect_event = asyncio.Event() @_ctx_.room.on("disconnected") def *_on_disconnected*(): logger.info("šŸ”Œ Room disconnected") disconnect_event.set() await disconnect_event.wait() # Cleanup await session.aclose() logger.info("šŸ‘‹ Session closed gracefully") if name == "__main__": cli.run_app(server)
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!