modern-winter-66316
12/05/2025, 4:22 AMtall-airline-16756
12/05/2025, 4:22 AMtall-airline-16756
12/05/2025, 4:22 AMmodern-winter-66316
12/05/2025, 4:23 AMtall-airline-16756
12/05/2025, 4:23 AMmodern-winter-66316
12/05/2025, 4:24 AMtall-airline-16756
12/05/2025, 4:24 AMVOICE_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.modern-winter-66316
12/05/2025, 4:30 AMtall-airline-16756
12/05/2025, 4:31 AMnormalized_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.modern-winter-66316
12/05/2025, 4:35 AMJSON.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.modern-winter-66316
12/05/2025, 4:35 AMtall-airline-16756
12/05/2025, 4:36 AMtts=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.modern-winter-66316
12/05/2025, 6:00 AMagent/main.py)
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)
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)
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)
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)
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.tall-airline-16756
12/05/2025, 6:01 AMmetadata 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.modern-winter-66316
12/05/2025, 6:03 AMtall-airline-16756
12/05/2025, 6:03 AMprovider 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:
# 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.modern-winter-66316
12/05/2025, 6:18 AMmodern-winter-66316
12/05/2025, 6:19 AMtall-airline-16756
12/05/2025, 6:19 AMtall-airline-16756
12/05/2025, 6:20 AMmodern-winter-66316
12/05/2025, 6:22 AMRoomIO -> 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 providertall-airline-16756
12/05/2025, 6:23 AMmodern-winter-66316
12/05/2025, 6:27 AMtall-airline-16756
12/05/2025, 6:28 AMAgentSession 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 docsmodern-winter-66316
12/05/2025, 6:29 AMtall-airline-16756
12/05/2025, 6:30 AMagentName: "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 processingmodern-winter-66316
12/05/2025, 9:08 PMDebugClient] 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-1764968840767tall-airline-16756
12/05/2025, 9:09 PM"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 docsmodern-winter-66316
12/05/2025, 9:10 PMmodern-winter-66316
12/05/2025, 9:11 PMtall-airline-16756
12/05/2025, 9:13 PMvoice = 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.