enough-pilot-49245
09/25/2025, 5:42 AMRoomIO -> AgentSession -> TranscriptSynchronizer -> DataStreamIO {"pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"}
2025-09-24 234104,171 - WARNING livekit.agents - resume_false_interruption is enabled but audio output does not support pause, it will be ignored {"audio_output": "TranscriptSynchronizer", "pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"}
2025-09-24 234104,171 - DEBUG livekit.agents - using transcript io: AgentSession -> TranscriptSynchronizer -> RoomIO {"pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"}
2025-09-24 234104,171 - DEBUG livekit.agents - using video io: RoomIO > AgentSession > (none) {"pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"}
2025-09-24 234104,630 - DEBUG livekit.agents - remote participant ready {"identity": "simli-avatar-agent", "pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"}
2025-09-24 234112,074 - WARNING livekit.agents - failed to synthesize speech, retrying in 0.1s
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 358, in _run
connection = await asyncio.wait_for(
^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/tasks.py", line 489, in wait_for
return fut.result()
^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 239, in current_connection
await conn.connect()
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 513, in connect
self._ws = await self._session.ws_connect(url, headers=headers)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 1084, in _ws_connect
raise WSServerHandshakeError(
aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url='https://help.elevenlabs.io/hc/en-us/articles/22497891312401-Do-you-restrict-access-to-the-service-and-platform-for-any-specific-countries-add'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task
await self._run(output_emitter)
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 364, in _run
raise APIConnectionError("could not connect to ElevenLabs") from e
livekit.agents._exceptions.APIConnectionError: could not connect to ElevenLabs (body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 1, "streamed": true, "pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"}
2025-09-24 234115,679 - WARNING livekit.agents - failed to synthesize speech, retrying in 2.0s
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 358, in _run
connection = await asyncio.wait_for(
^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/tasks.py", line 489, in wait_for
return fut.result()
^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 239, in current_connection
await conn.connect()
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 513, in connect
self._ws = await self._session.ws_connect(url, headers=headers)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 1084, in _ws_connect
raise WSServerHandshakeError(
aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url='https://help.elevenlabs.io/hc/en-us/articles/22497891312401-Do-you-restrict-access-to-the-service-and-platform-for-any-specific-countries-add'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task
await self._run(output_emitter)
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 364, in _run
raise APIConnectionError("could not connect to ElevenLabs") from e
livekit.agents._exceptions.APIConnectionError: could not connect to ElevenLabs (body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 2, "streamed": true, "pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"}
2025-09-24 234119,201 - WARNING livekit.agents - failed to synthesize speech, retrying in 2.0s
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 358, in _run
connection = await asyncio.wait_for(
^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/tasks.py", line 489, in wait_for
return fut.result()
^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 239, in current_connection
await conn.connect()
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 513, in connect
self._ws = await self._session.ws_connect(url, headers=headers)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 1084, in _ws_connect
raise WSServerHandshakeError(
aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url='https://help.elevenlabs.io/hc/en-us/articles/22497891312401-Do-you-restrict-access-to-the-service-and-platform-for-any-specific-countries-add'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task
await self._run(output_emitter)
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 364, in _run
raise APIConnectionError("could not connect to ElevenLabs") from e
livekit.agents._exceptions.APIConnectionError: could not connect to ElevenLabs (body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 3, "streamed": true, "pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"}
2025-09-24 234123,034 - ERROR livekit.agents - Error in _tts_inference_task
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 358, in _run
connection = await asyncio.wait_for(
^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/tasks.py", line 489, in wait_for
return fut.result()
^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 239, in current_connection
await conn.connect()
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 513, in connect
self._ws = await self._session.ws_connect(url, headers=headers)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 1084, in _ws_connect
raise WSServerHandshakeError(
aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url='https://help.elevenlabs.io/hc/en-us/articles/22497891312401-Do-you-restrict-access-to-the-service-and-platform-for-any-specific-countries-add'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/voice/generation.py", line 212, in _tts_inference_task
async for audio_frame in tts_node:
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/voice/agent.py", line 436, in tts_node
async for ev in stream:
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 532, in anext
raise exc # noqa: B904
^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task
await self._run(output_emitter)
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 364, in _run
raise APIConnectionError("could not connect to ElevenLabs") from e
livekit.agents._exceptions.APIConnectionError: could not connect to ElevenLabs (body=None, retryable=True) {"pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"}tall-airline-16756
09/25/2025, 5:43 AMtall-airline-16756
09/25/2025, 5:43 AMELEVEN_API_KEY or that it’s properly passed as a parameter when initializing.
2. Next, make sure the API key has the necessary permissions for text-to-speech streaming.
3. It’s also a good idea to look into any network restrictions or firewall settings that might be blocking WebSocket connections to <wss://api.elevenlabs.io>.
4. Lastly, take a moment to review your initialization code to confirm the TTS class is set up correctly.
If you’re still running into trouble after these steps, it might be worth checking if there are any regional restrictions affecting access to ElevenLabs services. I’m here to help you through this, so don’t hesitate to reach out with any questions!
Sources: SIP troubleshooting guide | LiveKit Docs | livekit-plugins/livekit-plugins-elevenlabs/livekit/plugins/elevenlabs/stt.p... | plugins/elevenlabs/src/tts.ts | ElevenLabs TTS integration guide | LiveKit Docsbreezy-addition-94590
09/25/2025, 6:43 AMtall-airline-16756
09/25/2025, 6:44 AM<http://api.simli.ai|api.simli.ai> couldn’t be translated into an IP address. This is why the connection to the Simli AI service isn’t going through.
Let’s try a few steps to get this sorted out:
1. First, check the DNS resolution by running host <http://api.simli.ai|api.simli.ai> on the server or container where your LiveKit agent is running.
2. Make sure that outbound internet access on port 443 is allowed for external domains—sometimes firewalls can block these connections.
3. Also, take a look at any network initialization issues, especially if you’re working with cloud environments or container orchestration systems.
4. Try testing the connectivity directly with curl -v <https://api.simli.ai> to see what response you get.
5. It might help to switch to a reliable DNS resolver like Google DNS (8.8.8.8), just to be sure.
If you’re still running into trouble after these steps, it might be a good idea to reach out to your network administrator for a closer look. We’re here to help you through this!
Sources: livekit-plugins/livekit-plugins-inworld/livekit/plugins/inworld/tts.py | Configuring firewalls | LiveKit Docs | Deploy to a VM | LiveKit Docs | Diagnosing Connection Errors with Connection Test Utilitybreezy-addition-94590
09/25/2025, 7:58 AMtall-airline-16756
09/25/2025, 7:59 AMnavigence-85r0jkqk.livekit.cloud was unexpectedly reset by the server or something in the network. This can happen for a few common reasons:
• Network firewalls or security settings might be blocking traffic to *.livekit.cloud on port 443.
• There could be SSL/TLS handshake issues, like outdated certificates or incompatible TLS versions.
• The server might disconnect due to invalid credentials or timeouts.
Here are some friendly steps you can try to get this sorted out:
1. Make sure that outbound connections to *.livekit.cloud and *.turn.livekit.cloud on TCP port 443 are allowed.
2. Take a look at any firewall or antivirus software that might be affecting WebSocket connections.
3. Try using the LiveKit Connection Test Utility, especially the WebSocket and TURN checks, to see how the connection is doing.
4. Double-check that the server URL and access token you’re using are correct.
5. If you suspect SSL/TLS issues, consider updating your system or application certificate stores.
If you’re still running into trouble after these steps, it might be helpful to reach out to your IT team to ensure that traffic to the necessary domains is allowed. We're here to help you through this!
Sources: Operational Guidance | livekit/livekit_composite | DeepWiki | errors.go | Configuring firewalls | LiveKit Docs | Diagnosing Connection Errors with Connection Test Utilitybreezy-addition-94590
09/25/2025, 8:05 AMtall-airline-16756
09/25/2025, 8:05 AM*.turn.livekit.cloud or similar domains.
• Or, the server settings in your LiveKit configuration might need a quick review.
Here are some steps that can help you get this sorted out:
1. Try running the LiveKit Connection Test Utility to check your WebSocket, WebRTC, and TURN connectivity.
2. Make sure that domains like *.turn.livekit.cloud are allowed on your network, and that TCP/TLS traffic on port 443 is open.
3. To check for DNS issues, you can run host stun:ip-161-118-222-18.host.livekit.cloud and host turn:ip-161-118-222-18.host.livekit.cloud.
4. You might also want to try forcing TURN usage by setting iceTransportPolicy: 'relay' in your client configuration—this helps confirm TURN connectivity.
If you’re still running into problems after these steps, it could be helpful to reach out to your network administrator to double-check that the necessary domains and ports are accessible. Please know we’re here to support you through this!
Sources: Documentation/ImprovingCallReliability.md | README.md | pkg/service/roommanager.go | Configuring firewalls | LiveKit Docs | Diagnosing Connection Errors with Connection Test Utilitybreezy-addition-94590
09/25/2025, 8:12 PMRoomIO -> AgentSession -> TranscriptSynchronizer -> DataStreamIO {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113101,125 - WARNING livekit.agents - resume_false_interruption is enabled but audio output does not support pause, it will be ignored {"audio_output": "TranscriptSynchronizer", "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113101,125 - DEBUG livekit.agents - using transcript io: AgentSession -> TranscriptSynchronizer -> RoomIO {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113101,125 - DEBUG livekit.agents - using video io: RoomIO > AgentSession > (none) {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113101,466 - DEBUG livekit.agents - remote participant ready {"identity": "simli-avatar-agent", "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113103,400 - WARNING livekit.plugins.elevenlabs - websocket closed unexpectedly {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113103,404 - WARNING livekit.agents - failed to synthesize speech, retrying in 0.1s
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task
await self._run(output_emitter)
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 429, in _run
raise e
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 424, in _run
await waiter
livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 1, "streamed": true, "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113105,439 - WARNING livekit.plugins.elevenlabs - websocket closed unexpectedly {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113105,440 - WARNING livekit.agents - failed to synthesize speech, retrying in 2.0s
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task
await self._run(output_emitter)
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 429, in _run
raise e
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 424, in _run
await waiter
livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 2, "streamed": true, "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113109,363 - WARNING livekit.plugins.elevenlabs - websocket closed unexpectedly {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113109,364 - WARNING livekit.agents - failed to synthesize speech, retrying in 2.0s
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task
await self._run(output_emitter)
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 429, in _run
raise e
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 424, in _run
await waiter
livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 3, "streamed": true, "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113113,366 - WARNING livekit.plugins.elevenlabs - websocket closed unexpectedly {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"}
2025-09-25 113113,368 - ERROR livekit.agents - Error in _tts_inference_task
Traceback (most recent call last):
File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 529, in anext
val = await self._event_aiter.__anext__()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
StopAsyncIterationtall-airline-16756
09/25/2025, 8:12 PMbreezy-addition-94590
09/26/2025, 5:52 AMtall-airline-16756
09/26/2025, 5:53 AMbreezy-addition-94590
09/26/2025, 5:55 AMfrom dotenv import load_dotenv
import os,aiohttp,json
from livekit import agents
from livekit.agents import WorkerOptions, WorkerType,cli,AutoSubscribe,JobProcess
from livekit.agents import AgentSession, Agent, RoomInputOptions,metrics
from livekit.plugins import (
openai,
noise_cancellation,
simli,
elevenlabs,
silero
)
from jinja2 import Template
from livekit.agents.voice import MetricsCollectedEvent
from livekit.agents.metrics import LLMMetrics,STTMetrics,TTSMetrics
from app.core.config import settings
prompt_template=f"""You are an AI interviewer conducting a professional interview. Your interface with users will be voice, so you must avoid usage of unpronounceable punctuation and should use short and concise responses. Deliver the response in plain text without any Markdown or formatting.
You are conducting an interview for the position of {{job_title}} at {{company_name}}. This is a {{interview_type}} interview.
Your role is to:
1. Conduct a professional, engaging interview
2. Ask relevant questions based on the position and company
3. Listen actively to responses and ask follow-up questions
4. Maintain a friendly but professional tone
5. Guide the conversation naturally
6. Provide feedback when appropriate
7. Keep the interview flowing smoothly
Interview guidelines:
- Start with a warm welcome and brief introduction
- Ask 5-7 main questions plus follow-ups
- Allow the candidate to ask questions at the end
- Provide constructive feedback
- Keep responses concise and natural for voice interaction
- Be encouraging and supportive
Remember: You are speaking, not writing. Use natural speech patterns and avoid complex punctuation or formatting."""
def formate_template(data):
data=json.loads(data)
template = Template(prompt_template)
rendered_prompt = template.render(**data)
return rendered_prompt
def validate_configuration():
"""Validate that all required configuration is present"""
missing_configs = []
if not settings.OPENAI_API_KEY:
missing_configs.append("OPENAI_API_KEY")
if not settings.ELEVENLABS_API_KEY:
missing_configs.append("ELEVENLABS_API_KEY")
print("WARNING: ELEVENLABS_API_KEY not found. Will use OpenAI TTS as fallback.")
if not settings.SIMLI_API_KEY:
missing_configs.append("SIMLI_API_KEY")
print("WARNING: SIMLI_API_KEY not found. Avatar functionality will be disabled.")
if not settings.LIVEKIT_URL or not settings.LIVEKIT_API_KEY or not settings.LIVEKIT_API_SECRET:
missing_configs.extend(["LIVEKIT_URL", "LIVEKIT_API_KEY", "LIVEKIT_API_SECRET"])
if missing_configs:
print(f"Missing required configuration: {', '.join(missing_configs)}")
print("Please check your .env file and ensure all required API keys are set.")
return False
print("Configuration validation passed.")
return True
class Assistant(Agent):
def __init__(self,ctx) -> None:
super().__init__(instructions= formate_template(ctx.room.metadata))
def prewarm_process(proc: JobProcess):
proc.userdata["vad"] = silero.VAD.load(min_silence_duration=0.3)
async def entrypoint(ctx: agents.JobContext):
# Validate configuration first
validate_configuration()
await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
print(f"CTX.Room.Name: {ctx.room.name}")
metadata=json.loads(ctx.room.metadata)
# Prefer explicit voice_id from metadata; fallback to gender defaults
voice_id = metadata.get("voice_id")
if not voice_id:
if metadata.get('avatar_type', '').lower()=="female":
voice_id="21m00Tcm4TlvDq8ikWAM"
elif metadata.get('avatar_type', '').lower()=="male":
voice_id="GBv7mTt0atIp3Br8iCZE"
else:
voice_id = "21m00Tcm4TlvDq8ikWAM"
print("Agent Session")
total_llm_tokens = 0
total_stt_duration = 0.0
total_tts_duration = 0.0
def _on_metrics_collected(event: MetricsCollectedEvent):
# Use 'nonlocal' to modify variables from the outer scope
nonlocal total_llm_tokens, total_stt_duration, total_tts_duration
metrics = event.metrics
if isinstance(metrics, LLMMetrics):
# This is the missing block from your previous code
print("LLM METRICS RECEIVED:", metrics.model_dump())
tokens_used = metrics.completion_tokens
total_llm_tokens += tokens_used
print(f"Tokens Used in this turn: {tokens_used}")
elif isinstance(metrics, STTMetrics):
total_stt_duration += metrics.audio_duration
elif isinstance(metrics, TTSMetrics):
total_tts_duration += metrics.audio_duration
async def print_final_summary():
print("\n--- FINAL USAGE SUMMARY ---")
print(f"Total LLM Tokens Used: {total_llm_tokens}")
print(f"Total STT Audio Duration: {total_stt_duration:.2f} seconds")
print(f"Total TTS Audio Duration: {total_tts_duration:.2f} seconds")
print("---------------------------\n")
# Use only VAD to avoid turn-detector model requirement
# Initialize TTS with better error handling
tts_instance = None
try:
if settings.ELEVENLABS_API_KEY:
print(f"Initializing ElevenLabs TTS with voice_id: {voice_id}")
tts_instance = elevenlabs.TTS(
api_key=settings.ELEVENLABS_API_KEY,
voice_id=voice_id,
# Add connection timeout and retry settings
timeout=30.0,
retry_attempts=3
)
else:
print("ELEVENLABS_API_KEY not found, using OpenAI TTS as fallback")
tts_instance = openai.TTS(api_key=settings.OPENAI_API_KEY)
except Exception as e:
print(f"Failed to initialize ElevenLabs TTS: {e}")
print("Falling back to OpenAI TTS")
tts_instance = openai.TTS(api_key=settings.OPENAI_API_KEY)
session = AgentSession(
turn_detection=None,
vad=ctx.proc.userdata["vad"],
stt=openai.STT(api_key=settings.OPENAI_API_KEY),
tts=tts_instance,
allow_interruptions=True,
llm=openai.LLM(
model="gpt-4o-mini", # or gpt-4 / gpt-3.5-turbo depending on your needs
api_key=settings.OPENAI_API_KEY
),
max_endpointing_delay=0.3
)
async with aiohttp.ClientSession() as http_session:
enable_avatar = os.environ.get("SIMLI_ENABLE_AVATAR", "0") in ["1", "true", "True"]
avatar = None
if enable_avatar:
avatar_face_id = metadata.get("avatar_face_id") or metadata.get("face_id") or "cace3ef7-a4c4-425d-a8cf-a5358eb0c427"
avatar = simli.AvatarSession(
simli_config=simli.SimliConfig(
api_key=settings.SIMLI_API_KEY,
face_id=avatar_face_id,
),
)
try:
if avatar is not None:
print("Avatar Starting...")
await avatar.start(session, room=ctx.room)
else:
print("SIMLI_ENABLE_AVATAR disabled. Running audio-only agent.")
except Exception as e:
print(f"Failed to start avatar: {e}")
if avatar is not None:
print("Trying again with hardcoded conversation_id (NOT recommended for production)")
try:
avatar.conversation_id = metadata.get("session_id")
await avatar.start(session, room=ctx.room)
except Exception as e2:
print(f"Avatar failed again: {e2}")
print("Continuing with audio-only mode")
avatar = None
print("Agent Start")
print(f"Room:{ctx.room}")
print("ctx connect")
await ctx.connect()
session.on("metrics_collected", _on_metrics_collected)
ctx.add_shutdown_callback(print_final_summary)
await session.start(
room=ctx.room,
agent=Assistant(ctx),
room_input_options=RoomInputOptions(
noise_cancellation=noise_cancellation.BVC(),
video_enabled=True,
audio_enabled=True
),
)
print("generate Reply...")
greeting = f"""Hello! Welcome to your interview for the {metadata['job_title']} position at {metadata['company_name']}. I'm your AI interviewer, and I'm excited to learn more about you today. Let's start with a brief introduction. Can you tell me about yourself and what interests you about this role?"""
try:
await session.say(greeting)
except Exception as e:
print(f"Failed to say greeting: {e}")
# Continue without greeting if TTS fails
if __name__ == "__main__":
# agent_name ="Test"
agent_name =os.environ["AGENT_NAME"]
print(f"Agent_Name in creation: {agent_name}, Type: {type(agent_name)}")
opts = WorkerOptions(
entrypoint_fnc=entrypoint,
prewarm_fnc=prewarm_process,
worker_type=WorkerType.ROOM,
agent_name=agent_name,
initialize_process_timeout=90
)
cli.run_app(opts)tall-airline-16756
09/26/2025, 5:56 AMpreemptive_generation parameter in AgentSession.
2. Use Fast "Pre-Response" Fillers: While the main response is being prepared, your agent can quickly say things like "Let me think..." using a lightweight model—this keeps the conversation flowing naturally.
3. Optimize Network Proximity: Try to deploy your agent close to the services it uses (like LLM, STT, TTS) to reduce any network lag.
4. Monitor Metrics: Keep an eye on important performance indicators such as Time To First Token (TTFT) and latency for STT and TTS using the Agents Metrics API—this helps you spot and address any slowdowns.
5. Reduce Connection Setup Time: Using long-expiration tokens and dispatching agents during token generation can help minimize any idle waiting periods.
6. Optimize Data Loading: Preloading static data with the prewarm function and passing user-specific data through metadata can speed up initialization.
7. Leverage LiveKit Cloud: Deploying on LiveKit Cloud brings handy features like stateful load balancing, elastic scaling, and operational observability that boost performance.
These steps can really make your agent feel more responsive and efficient. If you’d like, I’d be happy to walk you through any of these tips in more detail—just let me know!
Sources: Docs::Agents | Agent Testing & Evaluation | livekit/livekit_composite | DeepWiki | Docs::Agents | Deploy and scale agents on LiveKit Cloud | Agent speech and audio | LiveKit Docs