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? If you’re unsure where to start, tell me what you’re trying to do with LiveKit (e.g., set up a room, join a call, record sessions, or troubleshoot an error) and any relevant details like project/room IDs, SDK (Web, iOS, Android), and a brief description of the issue.
m
can yu identify anythwing wrog with this code : .py +21 -5 from future import annotations import json import logging import os from enum import Enum from livekit.agents import AgentSession, JobContext, WorkerOptions, cli from livekit.agents.worker import ServerType from .agent import EnglishTeacherAgent from .scenarios import LEVEL_DEFAULT, SCENARIO_DEFAULT, Level, Scenario class VoiceProvider(str, Enum): LIVEKIT = "livekit" OPENAI_REALTIME = "openai_realtime" GEMINI_REALTIME = "gemini_realtime" VOICE_META_KEY = "voice_provider" VOICE_NAME_META_KEY = "voice" SCENARIO_META_KEY = "scenario" LEVEL_META_KEY = "level" async def entrypoint(ctx: JobContext) -> None: """Main entrypoint for LiveKit Worker with robust error handling.""" import logging import traceback logger = logging.getLogger("english-teacher-agent") try: # Validate JobContext and job before accessing if not ctx: logger.error("JobContext is None") raise ValueError("JobContext is None") if not hasattr(ctx, 'job') or not ctx.job: logger.error("ctx.job is None or missing") raise ValueError("ctx.job is None or missing") # Safely access metadata with validation metadata = ctx.job.metadata if hasattr(ctx.job, 'metadata') and ctx.job.metadata else {} if not isinstance(metadata, dict): logger.warning(f"Metadata is not a dict, got {type(metadata)}, using empty dict") metadata = {} # Safely access metadata with validation (support JSON string payloads) raw_metadata = ctx.job.metadata if hasattr(ctx.job, 'metadata') and ctx.job.metadata else {} metadata = {} if isinstance(raw_metadata, str): try: decoded = json.loads(raw_metadata) if isinstance(decoded, dict): metadata = decoded else: logger.warning( "Metadata JSON did not decode to dict, got %s; falling back to empty dict", type(decoded), ) except Exception as decode_err: logger.warning("Failed to decode metadata JSON '%s': %s", raw_metadata, decode_err) elif isinstance(raw_metadata, dict): metadata = raw_metadata else: logger.warning("Metadata is not a dict or JSON string, got %s; using empty dict", type(raw_metadata)) room_name = getattr(ctx.job, "room_name", None) or getattr(ctx.job, "room", None) if not room_name and getattr(ctx, "room", None): room_name = getattr(ctx.room, "name", None) logger.info("Agent job received: room=%s, metadata=%s", room_name or "unknown", metadata) logger.info( "Job details: job_id=%s, job_type=%s", getattr(ctx.job, "id", "N/A"), getattr(ctx.job, "type", "N/A"), ) logger.info( "Room details: room_name=%s, room_sid=%s", room_name or getattr(ctx.job, "room_name", "unknown"), getattr(ctx.job, "room_sid", getattr(ctx.job, "room_id", "N/A")), ) # Connect to LiveKit await ctx.connect() logger.info("Connected to LiveKit room") # Safely parse metadata with defaults scenario = _parse_scenario(metadata.get(SCENARIO_META_KEY)) level = _parse_level(metadata.get(LEVEL_META_KEY))
t
Thanks — I’m looking at the snippet you pasted. I can help find syntax/runtime issues and suggest fixes, but I need one quick clarification first: Do you want: 1) a static code review for obvious Python/syntax problems, or 2) help debugging a specific error you’re seeing when running this (please paste the traceback)? If you want a static review, I’ll start by checking imports, indentation, undefined names, and suspicious logic.
m
this si an agent that has several dioferent personas which ared slected in an htmlp app page but we only ever hear the default agent voice/ppersona
t
Thanks — I’ll help diagnose why only the default persona voice plays. A few quick clarifying questions so I can target the root cause: 1. How is the selected persona sent from the HTML app to the agent? (e.g., as job metadata key names/values, as query params, or via an API call). Please paste the exact metadata keys/values you send when selecting a persona. 2. Which metadata key does your code use to set the voice/persona? In the snippet I see
VOICE_META_KEY
and
VOICE_NAME_META_KEY
— which one does the client set? 3. Do you have the part of the agent code that reads the voice metadata and calls the voice provider (or sets the RT voice)? Please paste that function or the code path where
metadata
is used to choose the voice. 4. Are there any logs or tracebacks when a non-default persona is selected? If so, paste the relevant lines (logger.info/warning/error) showing metadata contents and any voice-selection logs. 5. Which SDK/transport is used for voice output (LiveKit TTS, external provider like OpenAI/Gemini, or streaming audio)? Name the provider you expect to use when selecting a persona. If you want, I can start a static review of the snippet you already posted and list likely issues that would cause fallback to default voice — say yes and I’ll proceed.
m
metadata = raw_metadata else: logger.warning("Metadata is not a dict or JSON string, got %s; using empty dict", type(raw_metadata)) metadata = {} room_name = getattr(ctx.job, "room_name", None) or getattr(ctx.job, "room", None) if not room_name and getattr(ctx, "room", None): room_name = getattr(ctx.room, "name", None) logger.info("Agent job received: room=%s, metadata=%s", room_name or "unknown", metadata) logger.info( "Job details: job_id=%s, job_type=%s", getattr(ctx.job, "id", "N/A"), getattr(ctx.job, "type", "N/A"), ) logger.info( "Room details: room_name=%s, room_sid=%s", room_name or getattr(ctx.job, "room_name", "unknown"), getattr(ctx.job, "room_sid", getattr(ctx.job, "room_id", "N/A")), ) # Connect to LiveKit await ctx.connect() logger.info("Connected to LiveKit room") normalized_metadata = _normalize_metadata_keys(metadata) # Safely parse metadata with defaults scenario = _parse_scenario(metadata.get(SCENARIO_META_KEY)) level = _parse_level(metadata.get(LEVEL_META_KEY)) # Validate voice provider with safe fallback voice_provider_str = metadata.get(VOICE_META_KEY, VoiceProvider.LIVEKIT.value) try: provider = VoiceProvider(voice_provider_str) except ValueError: logger.warning(f"Invalid voice provider '{voice_provider_str}', defaulting to LIVEKIT") provider = VoiceProvider.LIVEKIT scenario = _parse_scenario(normalized_metadata.get(SCENARIO_META_KEY)) level = _parse_level(normalized_metadata.get(LEVEL_META_KEY)) provider, voice = _parse_voice_settings(normalized_metadata, logger) # For this project we only use LiveKit Inference (no external API keys). # Even if a different provider is requested, force LIVEKIT for safety. if provider is not VoiceProvider.LIVEKIT: logger.info( "Provider %s requested but this deployment is LiveKit-Inference-only; forcing LIVEKIT", provider.value, ) provider = VoiceProvider.LIVEKIT voice = metadata.get(VOICE_NAME_META_KEY, "default") if not isinstance(voice, str): voice = "default" logger.info(f"Starting agent: scenario={scenario.value}, level={level.value}, provider={provider.value}, voice={voice}") # Create agent instance agent = EnglishTeacherAgent(scenario=scenario, level=level) logger.info("EnglishTeacherAgent created successfully (persona=%s)", agent.persona.name) # Create session based on provider with error handling session = None try: if provider is VoiceProvider.OPENAI_REALTIME: from livekit.plugins import openai # Prefer persona-specific OpenAI voice when available openai_voice = agent.persona.openai_voice or (voice if voice != "default" else None) or "alloy" session = AgentSession( llm=openai.realtime.RealtimeModel( model=os.getenv("OPENAI_REALTIME_MODEL", "gpt-4o-realtime-preview-2024-10-01"), voice=openai_voice, instructions=agent.instructions, ), turn_detection="realtime_llm", ) logger.info("Using OpenAI Realtime API (voice=%s)", openai_voice) elif provider is VoiceProvider.GEMINI_REALTIME: @@ -207,50 +199,151 @@ async def entrypoint(ctx: JobContext) -> None: logger.error(traceback.format_exc()) # Re-raise to let LiveKit handle it raise def cli_entry() -> None: """CLI entrypoint that exposes console/dev/start commands.""" agent_name = os.getenv("AGENT_NAME") or None logger = logging.getLogger("english-teacher-agent") if agent_name: logger.info("Registering worker with explicit agent_name=%s", agent_name) else: logger.warning( "AGENT_NAME environment variable is not set; worker will register anonymously." ) cli.run_app( WorkerOptions( entrypoint_fnc=entrypoint, worker_type=ServerType.ROOM, agent_name=agent_name, ) ) def _normalize_metadata_keys(metadata: dict[str, object]) -> dict[str, object]: normalized: dict[str, object] = {} for key, value in metadata.items(): if isinstance(key, str): key_normalized = key.strip().lower().replace("-", "_") normalized[key_normalized] = value return normalized def _parse_voice_settings( metadata: dict[str, object], logger: logging.Logger ) -> tuple[VoiceProvider, str]: """Extract voice provider/voice from loosely formatted UI metadata. Accepts common variants like "provider", "voiceProvider", "speakerId", etc., and normalizes casing and hyphens so persona selections from the HTML UI are honored. """ provider_value = _first_metadata_value( metadata, [ VOICE_META_KEY, "voiceprovider", "provider", "voice_provider_name", "tts_provider", ], ) persona_block = metadata.get("persona") if provider_value is None and isinstance(persona_block, dict): provider_value = _first_metadata_value( _normalize_metadata_keys(persona_block), ["provider", "voice_provider"] ) provider = _coerce_provider(provider_value, logger) voice_value = _first_metadata_value( metadata, [ VOICE_NAME_META_KEY, "voice_name", "voiceid", "voicename", "speaker", "speaker_id", "speakerid", "persona", ], ) if isinstance(voice_value, dict): voice_value = _first_metadata_value( _normalize_metadata_keys(voice_value), ["voice", "voice_id", "voiceid", "speaker", "speaker_id"], ) voice = voice_value if isinstance(voice_value, str) and voice_value.strip() else "default" return provider, voice def _first_metadata_value(metadata: dict[str, object], keys: list[str]) -> object | None: for key in keys: if key in metadata: return metadata[key] return None def _coerce_provider(value: object | None, logger: logging.Logger) -> VoiceProvider: if isinstance(value, VoiceProvider): return value if isinstance(value, str): normalized = value.strip().lower().replace("-", "_") provider_aliases = { "lk": VoiceProvider.LIVEKIT, "livekit": VoiceProvider.LIVEKIT, "cartesia": VoiceProvider.LIVEKIT, "openai": VoiceProvider.OPENAI_REALTIME, "openai_realtime": VoiceProvider.OPENAI_REALTIME, "openai_realtime_api": VoiceProvider.OPENAI_REALTIME, "gemini": VoiceProvider.GEMINI_REALTIME, "google": VoiceProvider.GEMINI_REALTIME, "google_realtime": VoiceProvider.GEMINI_REALTIME, "gemini_realtime": VoiceProvider.GEMINI_REALTIME, } if normalized in provider_aliases: return provider_aliases[normalized] try: return VoiceProvider(normalized) except ValueError: logger.warning( "Invalid voice provider '%s', defaulting to LIVEKIT", value ) return VoiceProvider.LIVEKIT def _parse_scenario(value: str | None) -> Scenario: if not value: return SCENARIO_DEFAULT normalized = value.lower() for scenario in Scenario: if normalized in (scenario.name.lower(), scenario.value.split()[0]): return scenario return SCENARIO_DEFAULT def _parse_level(value: str | None) -> Level: if not value: return LEVEL_DEFAULT normalized = value.lower() for level in Level: if normalized in (level.name.lower(), level.value.lower()): return level return LEVEL_DEFAULT if name == "__main__":
t
Thanks — I’m responding about why only the default persona voice plays. Quick findings from your snippet: • You normalize metadata into
normalized_metadata
but you still read some values from the original
metadata
(for example
voice = metadata.get(VOICE_NAME_META_KEY, "default")
). That can cause persona selections to be ignored if the client sends keys with different casing/hyphens that only exist in
normalized_metadata
. • You force
provider = VoiceProvider.LIVEKIT
for this deployment. If the persona relies on a provider-specific voice (OpenAI/Gemini) that logic will be bypassed. •
_parse_voice_settings
returns a
(provider, voice)
pair but you call it and assign to
provider, voice = _parse_voice_settings(normalized_metadata, logger)
— then later you overwrite
voice
from
metadata
again. That overwrite can undo the parsed persona voice. • Normalization/ordering: you call `_parse_scenario`/`_parse_level` on both
metadata
and
normalized_metadata
at different points; inconsistent use may hide where the voice key actually lives. Concrete next steps to verify and fix: 1. Log the raw and normalized metadata right after normalization: ◦ Log
metadata
and
normalized_metadata
. ◦ Log the result of
_parse_voice_settings(normalized_metadata, logger)
(provider + voice). 1. Ensure you only read voice/provider from
normalized_metadata
after normalization. Replace the later
voice = metadata.get(VOICE_NAME_META_KEY, "default")
with
voice = normalized_metadata.get(VOICE_NAME_META_KEY, voice)
or trust the
_parse_voice_settings
return value without overwriting it. 2. If you must force LiveKit provider, ensure persona voices map to LiveKit voice names and that
agent.persona
has a
livekit_voice
(or similar) you prefer. Otherwise allow provider-specific voices when a persona requests them. 3. Confirm the exact metadata payload the HTML app sends. Example helpful format: ◦ keys and values (e.g., { "voiceProvider": "openai_realtime", "voiceName": "emma" } or nested persona block) ◦ whether it’s JSON string or object 1. Add a short runtime log before creating the session: ◦ logger.info("Resolved provider=%s, voice=%s, persona.openai_voice=%s, persona.livekit_voice=%s", provider, voice, agent.persona.openai_voice, getattr(agent.persona, "livekit_voice", None)) If you want, paste one example metadata payload from the HTML app and I’ll point out exactly how it will be parsed and show the minimal code change to preserve the selected persona voice.
m
• The HTML client posts JSON to /api/connect with keys scenario, level, voice_provider, and voice, so the request body looks like {"scenario":"...", "level":"...", "voice_provider":"openai_realtime", "voice":"alloy"} and is sent as a JSON string via fetch(... JSON.stringify(...)). • app.jsLines 91-122 • • • • const response = await fetch(apiEndpoint, { • method: "POST", • headers: { "Content-Type": "application/json" }, level, voice_provider, voice }`, and then serializes it with
JSON.stringify(metadata)
before attaching it both to the room and the agent dispatch, so the worker always receives a JSON string payload. ```62101api/connect.js • const scenario = typeof body.scenario === 'string' ? body.scenario : 'taxi'; • ... • const metadata = { scenario, level, voice_provider, voice }; • const agentDispatch = { • agentName: AGENT_NAME, • metadata: JSON.stringify(metadata), • }; • • • • • The server keeps that exact structure when creating the job metadata: it normalizes types, builds { scenario, level, voice_provider, voice }, and then serializes it with JSON.stringify(metadata) before attaching it both to the room and the agent dispatch, so the worker always receives a JSON string payload. • connect.jsLines 62-101 • • • • const scenario = typeof body.scenario === 'string' ? body.scenario : 'taxi'; • ... • const metadata = { scenario, level, voice_provider, voice }; • const agentDispatch = { • agentName: AGENT_NAME, • metadata: JSON.stringify(metadata), • };tadata being sent. • • • • • Added the requested runtime trace right after instantiating EnglishTeacherAgent, including safe getattr calls so the log won’t blow up even though agent.persona isn’t defined today. This gives clear visibility into the resolved provider/voice and any persona mapping you add later. • main.pyLines 101-116 • • • • logger.info(f"Starting agent: scenario={scenario.value}, level={level.value}, provider={provider.value}, voice={voice}") • agent = EnglishTeacherAgent(scenario=scenario, level=level) • ... • logger.info( • "Resolved provider=%s, voice=%s, persona.openaivoice=%s, persona.livekitvoice=%s", • provider.value, • voice, • persona_openai_voice, • persona_livekit_voice, • ) • • • • No automated tests were run (not requested). When you trigger a new session, watch the logs for the “Resolved provider=…” line; if the voice_provider or voice values aren’t what you expect, double-check the UI selection and metadata being sent.
does this help ?
t
Yes — this helps a lot. Summary and exact next steps to fix the issue (based on what you provided): Why only the default voice plays • The metadata arrives as a JSON string and you correctly parse/normalize it. Logs show the resolved provider and voice (e.g., provider=openai_realtime, voice=alloy). • The agent still uses a hardcoded TTS/voice when constructing the agent/session (e.g.,
tts=llm.TTS(name="azure")
or otherwise creating
AgentSession
with static voice). The parsed `provider`/`voice` are never applied to the TTS/RealtimeModel, so the default voice is used. Concrete fixes to apply now 1. Parse the JSON string into a dict (you already do this in entrypoint). Ensure you only use
normalized_metadata
after normalization. 2. Use the parsed provider/voice when creating the agent or session instead of overwriting them later. Example approaches: ◦ If agent accepts TTS params, pass them in when constructing the agent: ▪︎ agent = EnglishTeacherAgent(..., tts_params={"provider": provider, "voice": voice}) ◦ Or when creating the session, instantiate the correct model based on provider: ▪︎ For OpenAI Realtime: ▪︎ use
openai.realtime.RealtimeModel(model=..., voice=voice, instructions=agent.instructions)
when provider == OPENAI_REALTIME ▪︎ For LiveKit: map
voice
to the LiveKit inference voice name and use the LiveKit session config 1. Remove the late overwrite
voice = metadata.get(VOICE_NAME_META_KEY, "default")
— instead prefer the
voice
returned by
_parse_voice_settings(normalized_metadata, logger)
. 2. If you intentionally force
provider = LIVEKIT
, ensure the LiveKit voice mapping exists (e.g.,
agent.persona.livekit_voice
) and use that when configuring LiveKit TTS. Recommended minimal code change (pseudo): • After parsing: ◦ provider, voice = _parse_voice_settings(normalized_metadata, logger) ◦ # do not reassign voice from raw metadata • When constructing session: ◦ if provider is VoiceProvider.OPENAI_REALTIME: openai_voice = agent.persona.openai_voice or (voice if voice != "default" else None) or "alloy" session = AgentSession(llm=openai.realtime.RealtimeModel(..., voice=openai_voice, instructions=agent.instructions), ...) • elif provider is VoiceProvider.LIVEKIT: livekit_voice = agent.persona.livekit_voice or (voice if voice != "default" else None) configure LiveKit session to use livekit_voice What to check after applying • Trigger a session and confirm the runtime log line shows the resolved provider and voice you expect. • Confirm the session creation log shows the actual voice passed to the model (e.g., "Using OpenAI Realtime API (voice=alloy)" or similar). • If still wrong, paste the relevant logs around session creation and the AgentSession constructor and I’ll review. If you want, paste the EnglishTeacherAgent init signature (or the code that sets its TTS) and I’ll give the exact minimal diff to apply.
m
sot any errors here ' we can only get one agent type to talk : # LiveKit English Teacher – Key Code Snippets These excerpts capture the core behaviors reviewers should understand when auditing or debugging the agent. Each block references the live file that ships with the worker so Codex/LK assistants can cross-check quickly. --- ## Metadata normalization & logging (
agent/main.py
)
Copy code
python
VOICE_META_KEY = "voice_provider"
VOICE_NAME_META_KEY = "voice"
...

def _normalize_metadata(_raw_metadata_, _logger_: logging.Logger) -> Dict:
    """Normalize metadata into a dictionary, handling JSON strings safely."""
    metadata: Dict = {}
    _if_ isinstance(raw_metadata, str):
        _try_:
            decoded = json.loads(raw_metadata)
            _if_ isinstance(decoded, dict):
                metadata = decoded
            _else_:
                logger.warning(
                    "Metadata JSON did not decode to dict, got %s; falling back to empty dict",
                    type(decoded),
                )
        _except_ Exception _as_ decode_err:  _# pragma: no cover - defensive logging_
            logger.warning("Failed to decode metadata JSON '%s': %s", raw_metadata, decode_err)
    _elif_ isinstance(raw_metadata, dict):
        metadata = raw_metadata
    _else_:
        logger.warning("Metadata is not a dict or JSON string, got %s; using empty dict", type(raw_metadata))
    _return_ metadata
Why it matters: UI metadata arrives as a JSON string; this helper guarantees a dict and logs malformed payloads rather than crashing the worker. --- ## Entrypoint safety checks & scenario selection (
agent/main.py
)
Copy code
python
async def entrypoint(_ctx_: JobContext) -> None:
    logger = logging.getLogger("english-teacher-agent")
    ...
    raw_metadata = ctx.job.metadata _if_ hasattr(ctx.job, 'metadata') and ctx.job.metadata _else_ {}
    metadata = _normalize_metadata(raw_metadata, logger)
    ...
    scenario = _parse_scenario(metadata.get(SCENARIO_META_KEY))
    level = _parse_level(metadata.get(LEVEL_META_KEY))
    provider, voice = _parse_voice_settings(metadata, logger)
    logger.info(
        "Starting agent: scenario=%s, level=%s, provider=%s, voice=%s",
        scenario.value,
        level.value,
        provider.value,
        voice,
    )
Why it matters: Validates the
JobContext
, normalizes metadata, and logs the resolved configuration so reviewers can confirm persona/voice selections propagated from the UI. --- ## Voice-provider parsing (
agent/main.py
)
Copy code
python
def _parse_voice_settings(_metadata_: Dict, _logger_: logging.Logger) -> tuple[VoiceProvider, str]:
    voice_provider_str = metadata.get(VOICE_META_KEY, VoiceProvider.LIVEKIT.value)
    _try_:
        provider = VoiceProvider(voice_provider_str)
    _except_ ValueError:
        logger.warning("Invalid voice provider '%s', defaulting to LIVEKIT", voice_provider_str)
        provider = VoiceProvider.LIVEKIT

    voice = metadata.get(VOICE_NAME_META_KEY, "default")
    _if_ not isinstance(voice, str):
        voice = "default"

    _return_ provider, voice
Why it matters: Centralizes enum validation and fallbacks. If reviewers see unexpected default voices, this is the choke point to inspect. --- ## Session construction per provider (
agent/main.py
excerpt)
Copy code
python
_if_ provider is VoiceProvider.OPENAI_REALTIME:
    _from_ livekit.plugins _import_ openai
    session = AgentSession(
        _llm_=openai.realtime.RealtimeModel(
            _model_=os.getenv("OPENAI_REALTIME_MODEL", "gpt-4o-realtime-preview-2024-10-01"),
            _voice_=voice _if_ voice != "default" _else_ "alloy",
            _instructions_=agent.instructions,
        ),
        _turn_detection_="realtime_llm",
    )
_elif_ provider is VoiceProvider.GEMINI_REALTIME:
    _from_ livekit.plugins _import_ google
    session = AgentSession(
        _llm_=google.realtime.RealtimeModel(
            _model_=os.getenv("GEMINI_REALTIME_MODEL", "gemini-2.0-flash-live-001"),
            _voice_=voice _if_ voice != "default" _else_ "Puck",
            _instructions_=agent.instructions,
        ),
        _turn_detection_="realtime_llm",
    )
_else_:
    _from_ livekit.plugins _import_ inference
    tts_model = os.getenv("LIVEKIT_TTS_MODEL", "cartesia/sonic-2")
    _if_ voice != "default":
        tts_model = f"{tts_model}:{voice}"
    session = AgentSession(
        _stt_="deepgram/nova-3",
        _llm_="openai/gpt-4.1-mini",
        _tts_=tts_model,
        _vad_=inference.VAD(),
        _turn_detection_="vad",
    )
Why it matters: Shows exactly how each provider path is wired (models, voices, fallbacks) and where to tweak audio settings. --- ## Agent persona prompt & scoring (
agent/agent.py
)
Copy code
python
class EnglishTeacherAgent(Agent):
    def __init__(_self_, _scenario_: Scenario, _level_: Level) -> None:
        self.scenario = scenario
        self.level = level
        super().__init__(_instructions_=self._create_system_prompt())
        self.session_state: Optional[SessionState] = None
        self._session_task: Optional[asyncio.Task] = None

    def _create_system_prompt(_self_) -> str:
        _return_ f"""
You are an English teacher role-playing as a {self.scenario.value}.
...
At the end, break character briefly to give scores (1-10) for:
Vocabulary, Grammar, Fluency, Comprehension, and Overall.
Give one specific tip for improvement.
"""

    async def on_enter(_self_) -> None:
        self.session_state = SessionState(...)
        self._session_task = asyncio.create_task(self._session_timer())
        _await_ self.session.generate_reply(
            _instructions_="Greet the student and introduce the scenario"
        )

    async def on_user_turn_completed(_self_, _turn_ctx_, _new_message_) -> None:
        _if_ self.session_state:
            self.session_state.scorer.assess_response(new_message.content)
Why it matters: Defines the persona instructions, session lifecycle, and scoring hook used every user turn—core for behavior reviews. --- Feel free to extend this document with additional snippets (e.g., scenarios or scoring logic) as reviewers request deeper context.
t
Thanks — this is very helpful. Summary and exact next steps based on your snippets: 1) Confirmed root cause • Metadata is sent as a JSON string and you correctly parse/normalize it; logs show resolved values (e.g., provider=openai_realtime, voice=alloy). • The session construction code uses the parsed provider/voice to build provider-specific models, but the agent still falls back to a default voice when running because either: ◦ A later overwrite uses the raw
metadata
instead of the normalized/parsed values, or ◦ The agent/tts configuration is still hardcoded (e.g., agent construction or session defaults override the parsed voice). 2) Immediate checks to run now • Trigger a session and paste the logs that show: ◦ The "Starting agent: scenario=..., provider=..., voice=..." line. ◦ The lines right after that which show which provider branch is taken and the session creation log (e.g., "Using OpenAI Realtime API (voice=...)" or the LiveKit TTS model chosen). • Confirm which single agent voice currently works (which provider + voice string produces audible non-default voice). 3) Minimal code changes to guarantee persona voice is used • Remove any later assignment that overwrites the parsed result. Keep and use the tuple returned by: ◦ provider, voice = _parse_voice_settings(metadata, logger) • Use those values directly when constructing session: ◦ For OpenAI Realtime: ▪︎ openai_voice = agent.persona.openai_voice or (voice if voice != "default" else None) or "alloy" ▪︎ session = AgentSession(llm=openai.realtime.RealtimeModel(..., voice=openai_voice, instructions=agent.instructions), ...) ◦ For Gemini Realtime: same pattern using
voice
or persona mapping. ◦ For LiveKit inference: ▪︎ map
voice
to the LiveKit TTS name (e.g.,
tts_model = f"{base}:{voice}"
only if
voice != "default"
), then pass it to AgentSession as in your snippet. • Ensure you do not force
provider = LIVEKIT
unless you also map persona voices into LiveKit names on
agent.persona
. 4) Quick debug logging to add (one-liners) • Right after normalization: ◦ logger.info("normalized_metadata=%s", metadata) • Right after parsing voice settings: ◦ logger.info("resolved provider=%s, voice=%s", provider.value, voice) • Immediately before session creation: ◦ logger.info("creating session for provider=%s with voice=%s", provider.value, voice) 5) If you want, next step I can do for you • Paste the EnglishTeacherAgent init (or the code that picks TTS when the Agent is created). I’ll return the exact minimal diff to inject the dynamic `tts`/`llm` selection so personas chosen in the UI are used end-to-end. Tell me which logs you see after running the checks (from step 2) or paste the agent init and I’ll give the precise code change.
m
class EnglishTeacherAgent(Agent): """English teacher agent that runs within a LiveKit AgentSession.""" def __init__(self, _scenario_: Scenario, _level_: Level) -> None: self.scenario = scenario self.level = level super().__init__(instructions=self._create_system_prompt()) self.session_state: Optional[SessionState] = None self._session_task: Optional[asyncio.Task] = None def _create_system_prompt(self) -> str: return f""" You are an English teacher role-playing as a {self.scenario.value}. ... Give one specific tip for improvement. """ session = None _try_: if provider is VoiceProvider.OPENAI_REALTIME: from livekit.plugins import openai session = AgentSession( llm=openai.realtime.RealtimeModel( model=os.getenv("OPENAI_REALTIME_MODEL", "gpt-4o-realtime-preview-2024-10-01"), voice=voice if voice != "default" else "alloy", instructions=agent.instructions, ), _turn_detection_="realtime_llm", ) elif provider is VoiceProvider.GEMINI_REALTIME: from livekit.plugins import google session = AgentSession( llm=google.realtime.RealtimeModel( model=os.getenv("GEMINI_REALTIME_MODEL", "gemini-2.0-flash-live-001"), voice=voice if voice != "default" else "Puck", instructions=agent.instructions, ), _turn_detection_="realtime_llm", ) _else_: from livekit.plugins import inference tts_model = os.getenv("LIVEKIT_TTS_MODEL", "cartesia/sonic-2") if voice != "default": tts_model = f"{tts_model}:{voice}" session = AgentSession( stt="deepgram/nova-3", llm="openai/gpt-4.1-mini", tts=tts_model, vad=inference.VAD(), _turn_detection_="vad", )
t
You're almost there — the issue is that session creation uses
provider
and
voice
values, but those parsed values aren't being passed into the agent construction or used consistently. Make these minimal changes so the UI selection is honored end-to-end. 1) Ensure you pass parsed provider/voice into session creation (do this where you create the AgentSession). Replace the current branching with code that uses the already-resolved
provider
and
voice
variables (do not re-read
metadata
afterward). Minimal pattern to apply (pseudo-diff): • Remove any later overwrite of
voice
from raw metadata. • Use the parsed values when creating sessions:
Copy code
# provider, voice already parsed earlier: provider: VoiceProvider, voice: str
if provider is VoiceProvider.OPENAI_REALTIME:
    from livekit.plugins import openai
    openai_voice = agent.persona.openai_voice or (voice if voice != "default" else None) or "alloy"
    session = AgentSession(
        llm=openai.realtime.RealtimeModel(
            model=os.getenv("OPENAI_REALTIME_MODEL", "gpt-4o-realtime-preview-2024-10-01"),
            voice=openai_voice,
            instructions=agent.instructions,
        ),
        turn_detection="realtime_llm",
    )
elif provider is VoiceProvider.GEMINI_REALTIME:
    from livekit.plugins import google
    gemini_voice = agent.persona.gemini_voice or (voice if voice != "default" else None) or "Puck"
    session = AgentSession(
        llm=google.realtime.RealtimeModel(
            model=os.getenv("GEMINI_REALTIME_MODEL", "gemini-2.0-flash-live-001"),
            voice=gemini_voice,
            instructions=agent.instructions,
        ),
        turn_detection="realtime_llm",
    )
else:  # LIVEKIT inference
    from livekit.plugins import inference
    base = os.getenv("LIVEKIT_TTS_MODEL", "cartesia/sonic-2")
    tts_model = f"{base}:{voice}" if voice != "default" else base
    session = AgentSession(
        stt="deepgram/nova-3",
        llm="openai/gpt-4.1-mini",
        tts=tts_model,
        vad=inference.VAD(),
        turn_detection="vad",
    )
2) Add two quick logs to confirm values at runtime: • After normalization/parsing: logger.info("normalized_metadata=%s", metadata) logger.info("resolved provider=%s, voice=%s", provider.value, voice) • Immediately before session creation: logger.info("creating session for provider=%s with voice=%s", provider.value, voice) 3) If you force provider->LIVEKIT anywhere, remove or conditionally allow provider-specific routing. If you must keep forcing LiveKit, map persona voices into LiveKit names (e.g.,
agent.persona.livekit_voice
) and use that when building
tts_model
. If you want, paste the exact lines around where you call
provider, voice = _parse_voice_settings(...)
and the session-creation block currently in your file; I’ll return a one-file patch with the minimal edits.
m
i am noticing we are getting 3 participants :
could tghis be an issue ?
t
Thanks — I’m responding about the new observation (three participants) and next steps to confirm whether it’s related. Quick checks to run now • Which participant identities/names do you see in the dashboard? Copy the exact names/IDs shown. • Which clients you expect to be in the room (e.g., one browser client + one agent session)? Describe where each client originates (HTML app, worker/agent, any monitoring/bot). • When you create the job, are you attaching metadata to both the room and the agent dispatch? If yes, that can create an extra participant (the agent session + the room join) — confirm whether your server calls both room.connect and agent dispatch. Likely causes • The worker/AgentSession may be joining the room as a participant in addition to the browser client, producing multiple participants (e.g., browser student, agent voice participant, and a monitor/bot). • If your server attaches the same metadata to both the room and the agent dispatch, you may be creating both a room-attached participant and a separate agent participant. • Retries or duplicated dispatches (double POST) can create extra participants. Immediate actionable steps 1. Paste the participant names/IDs from the dashboard and the logs around the time a session starts (room join logs, AgentSession creation logs). 2. Check server flow: confirm whether you call the LiveKit room join API for the agent in addition to dispatching the agent job. If so, avoid the extra join or use a distinct identity for the agent. 3. Add a short log when each client joins (client type, identity, source): logger.info("join: identity=%s, source=%s", identity, source) so you can map dashboard participants to code paths. 4. Search server logs for duplicate dispatches or repeated POSTs to /api/connect around the timestamp the extra participant appears. Send me: • the three participant names/IDs you see, and • the server/worker logs at session start (the "Starting agent..." and "creating session..." lines plus any room join logs). I’ll map those names to the code flow and show the minimal change to avoid the extra participant.
Seeing three participants can indeed be related. It often means an extra client or agent instance joined with default settings, which can cause the heard voice to be the default. Here’s a concise plan to confirm and fix it. 1) Identify participants • Copy the three participant identities/IDs from the dashboard. • Note which you expect (browser client identity, agent identity). 2) Check likely causes • Worker/AgentSession joined the room in addition to the browser client (agent voice participant). • Server attaches metadata to both room and agent dispatch, creating separate joins. • Duplicate dispatches or retries created a second agent instance. 3) Quick runtime checks (add these logs) • On every join: logger.info("join: identity=%s, source=%s, metadata=%s", identity, source, metadata) • Before creating AgentSession: logger.info("creating session: identity=%s, provider=%s, voice=%s", agent_identity, provider.value, voice) • On dispatch: log the agent dispatch identity and the room join call. 4) Immediate actions to prevent duplicates • Ensure you only call one join for the agent: either dispatch the agent job (AgentSession joins) OR perform a server-side room join—do not do both. • If you must attach metadata to the room and the agent, ensure metadata for the room join is minimal and the agent dispatch contains the persona payload; avoid dispatching a second join identity. • Dedupe dispatches: add an idempotency key on your server for the /api/connect flow to avoid double POST handling. 5) What to send me • The three participant names/IDs. • Logs around session start: room joins, "Starting agent..." line, and "creating session..." lines. I’ll map participants to code paths and show the exact minimal change to stop the extra join and ensure the selected persona voice is used.
m
doe stghis help : 5 Dec, 191015.293 livekit.agents input stream attached 05 Dec, 191015.294 livekit.agents input stream detached 05 Dec, 191015.294 livekit.agents input stream attached 05 Dec, 191015.302 livekit.agents http_session(): creating a new httpclient ctx 05 Dec, 191015.321 livekit livekit_api:signal clientsignal stream92livekit apisignal client:signal_stream - connecting to wss://turbo-ms4yz8cm.livekit.cloud/rtc?sdk=python&protocol=16&auto_subscribe=1&adaptive_stream=0&version=1.0.20 05 Dec, 191015.379 livekit rustls:anchors150rustls:anchors - add_parsable_certificates processed 150 valid and 0 invalid certs 05 Dec, 191015.380 livekit tokio_tungstenite:tlsencryptionrustls103tokio tungstenitetlsencryption:rustls - Added 150/150 native root certificates (ignored 0) 05 Dec, 191015.380 livekit rustls:clienths73rustlsclient:hs - No cached session for DnsName("turbo-ms4yz8cm.livekit.cloud") 05 Dec, 191015.381 livekit rustls:clienths132rustlsclient:hs - Not resuming any session 05 Dec, 191015.383 livekit rustls:clienths615rustlsclient:hs - Using ciphersuite TLS13_AES_128_GCM_SHA256 05 Dec, 191015.383 livekit rustls:clienttls13142rustlsclient:tls13 - Not resuming 05 Dec, 191015.384 livekit rustls:clienttls13381rustlsclient:tls13 - TLS1.3 encrypted extensions: [] 05 Dec, 191015.384 livekit rustls:clienths472rustlsclient:hs - ALPN protocol is None 05 Dec, 191015.430 livekit tungstenite:🤝client95tungstenite🤝:client - Client handshake done. 05 Dec, 191015.550 livekit.agents using audio io:
RoomIO
->
RecorderIO
->
AgentSession
->
RecorderIO
->
TranscriptSynchronizer
->
RoomIO
05 Dec, 191015.551 livekit.agents using transcript io:
AgentSession
->
TranscriptSynchronizer
->
RoomIO
05 Dec, 191016.401 livekit.agents start reading stream 05 Dec, 191020.294 urllib3.connectionpool Starting new HTTPS connection (1): turbo-ms4yz8cm.livekit.cloud:443 05 Dec, 191020.297 urllib3.connectionpool Starting new HTTPS connection (1): turbo-ms4yz8cm.livekit.cloud:443 05 Dec, 191020.681 urllib3.connectionpool https://turbo-ms4yz8cm.livekit.cloud:443 "POST /observability/traces/otlp/v0 HTTP/1.1" 200 0 05 Dec, 191020.854 urllib3.connectionpool https://turbo-ms4yz8cm.livekit.cloud:443 "POST /observability/logs/otlp/v0 HTTP/1.1" 200 0 05 Dec, 191022.662 livekit.agents Input is shorter by 16654 samples; silence has been prepended to align the input channel. The resulting recording may not accurately reflect the original audio. 05 Dec, 191026.042 urllib3.connectionpool https://turbo-ms4yz8cm.livekit.cloud:443 "POST /observability/traces/otlp/v0 HTTP/1.1" 200 0 05 Dec, 191026.214 urllib3.connectionpool https://turbo-ms4yz8cm.livekit.cloud:443 "POST /observability/logs/otlp/v0 HTTP/1.1" 200 0 05 Dec, 191029.711 livekit.agents closing agent session due to participant disconnect (disable via
RoomInputOptions.close_on_disconnect=False
) 05 Dec, 191029.712 livekit.agents stream closed 05 Dec, 191029.721 livekit.agents input stream detached 05 Dec, 191029.734 livekit.agents session closed 05 Dec, 191031.403 urllib3.connectionpool https://turbo-ms4yz8cm.livekit.cloud:443 "POST /observability/traces/otlp/v0 HTTP/1.1" 200 0 05 Dec, 191031.575 urllib3.connectionpool https://turbo-ms4yz8cm.livekit.cloud:443 "POST /observability/logs/otlp/v0 HTTP/1.1" 200 0 05 Dec, 191036.934 urllib3.connectionpool https://turbo-ms4yz8cm.livekit.cloud:443 "POST /observability/logs/otlp/v0 HTTP/1.1" 200 0 05 Dec, 191042.294 urllib3.connectionpool https://turbo-ms4yz8cm.livekit.cloud:443 "POST /observability/logs/otlp/v0 HTTP/1.1" 200 0 05 Dec, 191047.653 urllib3.connectionpool https://turbo-ms4yz8cm.livekit.cloud:443 "POST /observability/logs/otlp/v0 HTTP/1.1" 200 0 05 Dec, 191049.741 livekit tungstenite:protocol666tungstenite:protocol - Received close frame: Some(CloseFrame { code: Normal, reason: "" }) 05 Dec, 191049.742 livekit tungstenite:protocol683tungstenite:protocol - Replying to close with Frame { header: FrameHeader { is_final: true, rsv1: false, rsv2: false, rsv3: false, opcode: Control(Close), mask: None }, payload: [3, 232] } 05 Dec, 191049.753 livekit.agents uploading session report to LiveKit Cloud 05 Dec, 191049.757 livekit livekit:room1400livekit:room - disconnected from room with reason: RoomClosed 05 Dec, 191050.384 livekit.agents finished uploading 05 Dec, 191050.385 livekit.agents shutting down job task 05 Dec, 191050.386 livekit.agents shutting down telemetry tracer provider 05 Dec, 191050.387 livekit.agents shutting down telemetry logger provider
t
Thanks — the logs help. They show the agent connects, attaches audio IO, runs, then the session closes when a participant disconnects. To move forward I need two specific things to confirm whether the extra participants are causing the default-voice fallback: 1) Paste the three participant identities exactly as shown in the dashboard (names/IDs). 2) Paste the worker logs around session start that include these lines (if present): • "Starting agent: scenario=..., provider=..., voice=..." • The session-creation log such as "Using OpenAI Realtime API (voice=...)" or the LiveKit TTS model line. Quick observations from your logs: • The agent joined and attached RoomIO -> AgentSession chains, so the worker is creating an audio participant. • The session closed due to participant disconnect — this suggests the agent session lifecycle is tied to a participant join; if there are duplicate joins the agent may pick the wrong identity/metadata. • No obvious errors in network/TLS; traces/logs posted to LiveKit succeeded. Next steps I’ll take after you paste the two items above: • Map each participant identity to the join path (browser vs agent vs duplicate). • Confirm the resolved provider/voice used to construct AgentSession and whether it was overwritten. • Provide the exact 2–3 line code diff to fix any overwrite or duplicate join. Paste the participant names and the two log lines and I’ll give the precise next fix.
m
Publishers Participant identity Name Location Tracks Region Used features agent-AJ_Lh35XmcL9vdr —5 Dec 2025, 191015United States US East 1 5 Dec 2025, 191049— user-1764915015283 English Teacher Student 5 Dec 2025, 191015New Zealand Australia 5 Dec 2025, 191029— Subscribers Participant identity Name Location Region Used features agent-AJ_jgZw66jFuVbR —5 Dec 2025, 191015United States US East 1 5 Dec 2025, 191049—
t
Thanks — this is very helpful. You have two agent participants (one publisher, one subscriber). That likely explains the behavior: the participant publishing audio may not be the agent instance initialized with the selected persona, so you hear the default voice. What to do next (concise): 1) Confirm mapping • From the dashboard: the three identities you posted are: ◦ agent-AJ_Lh35XmcL9vdr (publisher) ◦ user-1764915015283 (browser student) ◦ agent-AJ_jgZw66jFuVbR (subscriber) • The publisher/subscriber pair shows the worker created an avatar/agent publisher plus a separate subscriber identity — the publisher is the one actually sending audio. 2) Quick checks to run now • Add logs when each participant joins/publishes: ◦ logger.info("join: identity=%s, kind=%s, source=%s, metadata=%s", identity, kind, source, ctx.job.metadata) • Log which identity
AgentSession
publishes on behalf of (look for
lk.publish_on_behalf
or agent session identity in worker logs). • Search server logs for duplicate dispatches or double POST to /api/connect around 191015. 3) Fixes to apply • Avoid double joins: ensure your server does not both (A) perform a room join for the agent and (B) dispatch an agent job that also joins. Only dispatch the agent job (preferred) or only join from server — not both. • Ensure metadata JSON string is parsed and used by the exact agent instance that will publish audio: ◦ Call
metadata = json.loads(ctx.job.metadata)
(you already do) and pass
provider, voice = _parse_voice_settings(metadata, logger)
before creating the session. ◦ Do not overwrite
voice
later from raw metadata. • If your deployment uses avatar/virtual-publisher plugins, map persona voices to the publisher instance: ◦ If you force LiveKit provider, set
tts_model = f"{base}:{voice}"
using the parsed
voice
(not raw metadata). ◦ Or prefer provider-specific RealtimeModel creation when provider != LIVEKIT. 4) Verify after changes • Start a session and confirm logs: ◦ "Starting agent: ... provider=..., voice=..." ◦ "creating session for provider=... with voice=..." ◦ A single agent identity should appear as publisher; remove the extra subscriber agent identity. • Confirm audible persona matches the logged
voice
. If you want, I can give the exact 3–6 line patch to: • Prevent double-join on dispatch, and • Ensure
voice
from
_parse_voice_settings
is used when building
AgentSession
. Which patch would you like first: prevent duplicate agent joins, or apply the dynamic voice -> session wiring? Sources: Virtual avatar plugins | LiveKit Docs | ElevenLabs TTS | LiveKit Docs | Agent Builder | LiveKit docs | Job lifecycle | LiveKit docs
m
what i ahve notixced is that the actual agent we should be loading is CA_u7F8JBWQAtY7
t
Thanks — this is useful. You're saying the intended agent ID is CA_u7F8JBWQAtY7. Focus on two things: ensure the dispatch targets that agent, and ensure the publishing participant for that agent uses the parsed voice metadata. Do these quick checks and fixes: 1) Confirm dispatch targets the correct agent • On your server where you build agentDispatch, ensure
agentName: "CA_u7F8JBWQAtY7"
(exact match, case-sensitive) is sent in the job payload. • If you use WorkerOptions.agent_name or AGENT_NAME env var, set it to
CA_u7F8JBWQAtY7
so the worker registers as that agent when needed. • Log the dispatch payload before sending: logger.info("dispatching agent: %s", agentDispatch). 2) Verify the worker received the intended agent name • In entrypoint, log
getattr(ctx.job, "agentName", None)
and
getattr(ctx.job, "agent_name", None)
right after parsing metadata to confirm which agent the job targets. 3) Ensure the publishing participant is the correct agent instance • After await ctx.connect(), log the local participant identity used by the session (e.g., logger.info("local participant identity=%s", ctx.local_participant.identity) or inspect
room.local_participant
). • If you see two agent identities in the room, trace which one has
lk.publish_on_behalf
or which identity the AgentSession publishes as. 4) Prevent duplicate/junk agent participants • Do not both server-join and dispatch the agent into the same room. Only dispatch the agent job (preferred) or only server-join; remove the extra join. • Add an idempotency key for /api/connect to avoid duplicate dispatches. 5) Ensure parsed voice/provider is applied to the publishing agent • Confirm you call
provider, voice = _parse_voice_settings(normalized_metadata, logger)
and do NOT overwrite
voice
later. • Use those values when creating AgentSession (example for OpenAI): set
voice=openai_voice
in RealtimeModel; for LiveKit TTS build
tts_model = f"{base}:{voice}"
if voice != "default". • Log immediately before session creation: logger.info("creating session for agent=%s provider=%s voice=%s", agent_name, provider.value, voice) Send me: • The dispatch payload you send (exact JSON) and • The logs for dispatching and the two lines: the job agentName and the "creating session..." log. I’ll give the exact 3–6 line patch to (a) ensure dispatch targets CA_u7F8JBWQAtY7 and (b) force the publishing participant to use the parsed
voice
. Sources: Agent dispatch | LiveKit docs | Job lifecycle | LiveKit docs | How to set a fixed participant for agent audio processing
m
should we use agent name or the agent ID ?
Copy code
DebugClient] Requesting token from /api/connect-debug
[DebugClient] Token endpoint response: {
  "token": "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiRW5nbGlzaCBUZWFjaGVyIFN0dWRlbnQiLCJ2aWRlbyI6eyJyb29tIjoiZW5nbGlzaC10ZWFjaGVyLTE3NjQ5Njg4NDAyOTgtcHM0Zzl3ZSIsInJvb21Kb2luIjp0cnVlLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwicm9vbUNvbmZpZyI6eyJhZ2VudHMiOlt7ImFnZW50TmFtZSI6ImNsb3VkLWVuZ2xpc2gtdGVhY2hlciIsIm1ldGFkYXRhIjoie1wic2NlbmFyaW9cIjpcImRlYnVnXCIsXCJsZXZlbFwiOlwiZGVidWdcIixcInZvaWNlX3Byb3ZpZGVyXCI6XCJsaXZla2l0XCIsXCJ2b2ljZVwiOlwiZGVmYXVsdFwifSJ9XX0sImlzcyI6IkFQSVdwQnNBVEJrcjZhciIsImV4cCI6MTc2NDk2OTQ0MCwibmJmIjowLCJzdWIiOiJ1c2VyLTE3NjQ5Njg4NDA3NjcifQ.M_AT1vaDRmjtShdGZKKViYA2DUvmIjQXMQ-qFF1SLw8",
  "url": "wss://turbo-ms4yz8cm.livekit.cloud",
  "room": "english-teacher-1764968840298-ps4g9we",
  "metadata": {
    "scenario": "debug",
    "level": "debug",
    "voice_provider": "livekit",
    "voice": "default"
  },
  "dispatchId": null,
  "agentName": "cloud-english-teacher",
  "token_debug": {
    "name": "English Teacher Student",
    "video": {
      "room": "english-teacher-1764968840298-ps4g9we",
      "roomJoin": true,
      "canPublish": true,
      "canSubscribe": true,
      "canPublishData": true
    },
    "roomConfig": {
      "agents": [
        {
          "agentName": "cloud-english-teacher",
          "metadata": "{\"scenario\":\"debug\",\"level\":\"debug\",\"voice_provider\":\"livekit\",\"voice\":\"default\"}"
        }
      ]
    },
    "iss": "APIWpBsATBkr6ar",
    "exp": 1764969440,
    "nbf": 0,
    "sub": "user-1764968840767"
  }
}
[DebugClient] Decoded token payload: {
  "name": "English Teacher Student",
  "video": {
    "room": "english-teacher-1764968840298-ps4g9we",
    "roomJoin": true,
    "canPublish": true,
    "canSubscribe": true,
    "canPublishData": true
  },
  "roomConfig": {
    "agents": [
      {
        "agentName": "cloud-english-teacher",
        "metadata": "{\"scenario\":\"debug\",\"level\":\"debug\",\"voice_provider\":\"livekit\",\"voice\":\"default\"}"
      }
    ]
  },
  "iss": "APIWpBsATBkr6ar",
  "exp": 1764969440,
  "nbf": 0,
  "sub": "user-1764968840767"
}
[DebugClient] Connecting to wss://turbo-ms4yz8cm.livekit.cloud
[DebugClient] Connected. Local participant identity: user-1764968840767
[DebugClient] Published local audio track
[DebugClient] Staying connected for 30000ms to allow agent dispatch
[DebugClient] connectionQualityChanged excellent user-1764968840767
t
Use the agent name. • Dispatch and roomConfig must use the agent's name (agentName / agent_name), not the internal agent ID (e.g., CA_u7F8JBWQAtY7). Your token payload shows you're already sending
"agentName":"cloud-english-teacher"
— that is correct. What to verify next (quick checklist) 1. Server dispatch payload — confirm it contains the exact agent name you intend (case-sensitive). 2. Worker registration — if you set AGENT_NAME or WorkerOptions.agent_name, use the same agent name. 3. Job metadata — parse
ctx.job.metadata
(json.loads) and use `voice`/`voice_provider` when creating the AgentSession (do not overwrite later). 4. Avoid duplicate joins — only dispatch the agent (or server-join), not both; add idempotency to /api/connect to avoid double dispatches. If you want, I can: • Give the 3–6 line patch to ensure the dispatch uses the name and the AgentSession uses parsed
voice
, or • Review the exact dispatch JSON you send and produce the minimal code change. Which would you prefer? Sources: Agent dispatch | LiveKit docs | Agents Framework | livekit/livekit_composite | DeepWiki | Server-side | livekit/livekit_composite | DeepWiki | Deploying to production | LiveKit Docs | SIP dispatch rule | LiveKit docs
m
1. [App] Selected configuration: Object 1. publishing track Object 1. disconnect from room _{room: 'english-teacher-1764968943243-yurwndz', roomID: 'RM_YeCkUfcJrdTp', participant: 'user-1764968943760', pID: 'PA_MvLMaXkF72Fu'}_ 2. pID 3. : a. "PA_MvLMaXkF72Fu" 4. participant 5. : a. "user-1764968943760" 6. room 7. : a. "english-teacher-1764968943243-yurwndz" 8. roomID 9. : a. "RM_YeCkUfcJrdTp" 10. [[Prototype]] 11. : a. Object 12. constructor 13. : i. ƒ Object() 14. hasOwnProperty 15. : i. ƒ hasOwnProperty() 16. isPrototypeOf 17. : i. ƒ isPrototypeOf() 18. propertyIsEnumerable 19. : i. ƒ propertyIsEnumerable() 20. toLocaleString 21. : i. ƒ toLocaleString() 22. toString 23. : i. ƒ toString() 24. valueOf 25. : i. ƒ valueOf() 26. defineGetter 27. : i. _ƒ __defineGetter__()_ 28. defineSetter 29. : i. _ƒ __defineSetter__()_ 30. lookupGetter 31. : i. _ƒ __lookupGetter__()_ 32. lookupSetter 33. : i. _ƒ __lookupSetter__()_ 34. proto 35. : i. (...) 36. get proto 37. : i. _ƒ __proto__()_ 38. set proto 39. : i. _ƒ __proto__()_ 1. [App] Selected configuration: {scenario: 'taxi', level: 'basic', provider: 'livekit', voice: 'default'} 1. publishing track _{room: 'english-teacher-1764968992093-9q4jdd6', roomID: '', participant: 'user-1764968992405', pID: 'PA_6Fh6uWe8kd8m', trackID: undefined, …}_ 2. enabled 3. : a. true 4. kind 5. : a. "audio" 6. muted 7. : a. false 8. pID 9. : a. "PA_6Fh6uWe8kd8m" 10. participant 11. : a. "user-1764968992405" 12. room 13. : a. "english-teacher-1764968992093-9q4jdd6" 14. roomID 15. : a. "" 16. source 17. : a. "microphone" 18. streamID 19. : a. "097f1c01-93ae-4e65-803b-084261d524b1" 20. streamTrackID 21. : a. "097f1c01-93ae-4e65-803b-084261d524b1" 22. trackID 23. : a. undefined 24. [[Prototype]] 25. : a. Object 1. disconnect from room _{room: 'english-teacher-1764968992093-9q4jdd6', roomID: 'RM_rA68GfMrtsWU', participant: 'user-1764968992405', pID: 'PA_6Fh6uWe8kd8m'}_ 2. pID 3. : a. "PA_6Fh6uWe8kd8m" 4. participant 5. : a. "user-1764968992405" 6. room 7. : a. "english-teacher-1764968992093-9q4jdd6" 8. roomID 9. : a. "RM_rA68GfMrtsWU" 10. [[Prototype]] 11. : a. Object
agent is not speaking ?
t
Thanks — I’ll focus on why the agent isn’t speaking. Quick diagnosis from what you shared • The browser client is joining and publishing (user-... identities show published audio). • Agent dispatch appears in roomConfig and the worker runs, but the agent publishes either not at all or as a different agent identity. That explains silence: the publishing participant is the student, not the agent voice publisher, or the agent publisher is using default voice. Immediate checks I need from you (paste these lines) 1. The worker log lines showing agent startup: the "Starting agent: scenario=..., provider=..., voice=..." line. 2. The lines showing session creation such as "creating session for provider=... with voice=..." or "Using OpenAI Realtime API (voice=...)" or the LiveKit tts_model value. 3. The room participant list that shows which participant is publishing audio (copy the participant identity that has published audio tracks). Quick fixes to try now (minimal changes) • Ensure the worker uses parsed metadata and does NOT overwrite it later: ◦ provider, voice = _parse_voice_settings(metadata, logger) ◦ Do not run
voice = metadata.get(...)
after that. • Ensure only the agent worker publishes agent audio: ◦ Do not server-join the agent in addition to dispatching the agent job. ◦ If the browser should not publish while agent speaks, mute or stop publishing the browser audio during agent turns. • Add these logs immediately after ctx.connect() and before session creation: ◦ logger.info("job agent_name=%s, normalized_metadata=%s", getattr(ctx.job, "agentName", None), metadata) ◦ logger.info("creating session for provider=%s, voice=%s, local_identity=%s", provider.value, voice, getattr(ctx, "local_participant", None)) • Confirm agentName in dispatch matches the agent you intend (use agent name, not agent ID). If you paste items 1–3 above I’ll map which identity is publishing and give the exact 3–6 line patch to: • Force the agent to publish using the parsed
voice
, and/or • Prevent the duplicate participant so the correct agent speaks.