modern-winter-66316
12/04/2025, 7:00 AMtall-airline-16756
12/04/2025, 7:00 AMtall-airline-16756
12/04/2025, 7:00 AMmodern-winter-66316
12/04/2025, 7:01 AMtall-airline-16756
12/04/2025, 7:01 AMparticipant in the constructor?)
3. How is your microphone published? Are you publishing a local audio track from the testing user and seeing it listed in the room participant list?
4. Do you see any warnings or errors like “silence detected on local audio track”? Are noise suppression or mute controls enabled on your client?
5. Can you confirm the role of each participant (teacher, assessor, testing user) and whether any server-side participant filtering or permission rules are applied?
Answering these will let me recommend the next steps (audio routing checks, RoomInput/RoomIO settings to include your participant, or how to address silence detection). Would you like step-by-step checks once you share those details?
Sources: How to set a fixed participant for agent audio processing | Agents Framework | livekit/livekit_composite | DeepWiki | Understanding "silence detected on local audio track" warningmodern-winter-66316
12/04/2025, 7:01 AMtall-airline-16756
12/04/2025, 7:01 AMmodern-winter-66316
12/04/2025, 7:02 AMtall-airline-16756
12/04/2025, 7:02 AMparticipant or input filters?
8. Are there server-side participant permission rules, ACLs, or room policy that block the testing user’s audio?
9. Are teacher/assessor subscribing to the testing user’s audio track(s)? Do their clients show the testing user’s track in their subscription list?
10. Are there simultaneous publishes of tracks with the same name/ID causing conflicts?
11. Is network quality for the testing user poor (packet loss, high latency) at the time of testing?
12. Do problems occur only when both roles are present, or also when only one agent is present?
Potential issues to check and tests to run
• Muted or blocked track: Verify the testing user’s local mic is unmuted and `isMuted`/published state is true. Try republishing a new audio track.
• Participant filter / input routing: Agents may be set to process only specific participant IDs. Ensure RoomInput/RoomIO settings include the testing user’s participant ID.
• Single-agent identity conflicts: If one agent instance impersonates multiple roles using the same participant identity, role-based routing may ignore the testing user. Use distinct participant IDs per agent role.
• Voice activity detection / silence suppression: VAD or aggressive noise suppression may classify low-volume speech as silence. Temporarily disable VAD/noise suppression to test.
• Subscription issues: Confirm agents are subscribed to the testing user’s audio track and that subscription grants are correct.
• Track naming/ID collision: Ensure unique track IDs/names so agents don’t ignore or override the testing user’s track.
• SDK/platform compatibility: Verify both sides use compatible codecs and sample rates; test with a simple Web client publishing to confirm.
• Latency/packet loss: Run a network quality test; high loss can make audio effectively silent.
• Client permissions: Ensure browser/mobile mic permissions granted and active.
• Server-side routing logic: Check any custom server logic that routes or filters incoming tracks to agents; add logging around routing decisions.
• Simulate simplified scenario: Test with only teacher + testing user, then assessor + testing user to isolate which agent triggers the issue.
Suggested minimal debug steps (run in order)
1. Confirm testing user sees their local mic as published and unmuted. Republish a fresh mic track.
2. Have each agent list subscribed tracks; verify testing user’s track appears.
3. Disable VAD/noise-suppression on the testing user and test speaking.
4. Temporarily remove agent input filters so agents accept audio from all participants.
5. Test with only one agent present to isolate whether concurrency triggers the problem.
6. Check server logs for routing decisions and any publish/subscribe errors.
7. If still failing, capture a short client-side debug log (track publish events, subscription events, and any warnings) for the time window.
If you want, I can convert this checklist into a JSON or formatted script your AI agent can run step-by-step. Would you like that?modern-winter-66316
12/04/2025, 7:03 AMtall-airline-16756
12/04/2025, 7:03 AMmodern-winter-66316
12/04/2025, 7:04 AMtall-airline-16756
12/04/2025, 7:04 AM#!/usr/bin/env bash
# LK CLI diagnostic script for testing-user audio visibility/subscription
# Replace placeholders below before running
ROOM_NAME="<ROOM_NAME>"
TEST_ID="<TESTING_USER_ID>"
TEACHER_ID="<TEACHER_PARTICIPANT_ID>"
ASSESSOR_ID="<ASSESSOR_PARTICIPANT_ID>"
# Helper for printing
ok() { printf "\n[OK] %s\n" "$1"; }
warn() { printf "\n[WARN] %s\n" "$1"; }
err() { printf "\n[ERROR] %s\n" "$1"; }
# 1) List participants in room
echo "1) Listing participants in room: $ROOM_NAME"
lk room participants --room "$ROOM_NAME"
if [ $? -ne 0 ]; then
err "Failed to list participants. Check LK CLI auth and ROOM_NAME."
exit 2
fi
ok "Participants listed (above). Confirm $TEST_ID, $TEACHER_ID, $ASSESSOR_ID present."
# 2) Describe testing user participant (published tracks & mute state)
echo "2) Describing testing user: $TEST_ID"
lk room participant describe --room "$ROOM_NAME" --identity "$TEST_ID"
if [ $? -ne 0 ]; then
err "Failed to describe testing user. Participant may not exist."
exit 3
fi
ok "Check above output for published audio track(s) and mute/state."
# 3) Check teacher & assessor participants describe
echo "3) Describing teacher: $TEACHER_ID"
lk room participant describe --room "$ROOM_NAME" --identity "$TEACHER_ID"
echo "Describing assessor: $ASSESSOR_ID"
lk room participant describe --room "$ROOM_NAME" --identity "$ASSESSOR_ID"
ok "Verify teacher/assessor have expected identities and subscriptions listed."
# 4) List current subscriptions in the room
echo "4) Listing subscriptions for room"
lk room subscriptions --room "$ROOM_NAME"
if [ $? -ne 0 ]; then
warn "Subscriptions listing failed or unsupported. Continue with manual checks."
else
ok "Subscriptions listed. Look for entries subscribing $TEACHER_ID/$ASSESSOR_ID to $TEST_ID's audio track(s)."
fi
# 5) Quick search in server logs for publish/subscribe issues and silence/VAD warnings
echo "5) Tail server logs (last 200 lines) and filter common audio issues"
lk logs tail --service server --lines 200 | sed -n '/publish\|subscribe\|silence\|vad\|error\|warn/Ip' > /tmp/lk_audio_logs.txt
if [ -s /tmp/lk_audio_logs.txt ]; then
ok "Filtered recent logs saved to /tmp/lk_audio_logs.txt. Inspect for publish/subscribe errors or silence/VAD warnings."
else
warn "No matching log lines found in last 200 lines. You may need broader log range or different service."
fi
# 6) Verify testing user track existence via participant track list (explicit track IDs)
echo "6) Enumerating tracks from testing user (from participant describe output)"
TEST_TRACKS=$(lk room participant describe --room "$ROOM_NAME" --identity "$TEST_ID" --output json 2>/dev/null | jq -r '.tracks[]?.trackId' 2>/dev/null)
if [ -z "$TEST_TRACKS" ]; then
err "No tracks found for testing user ($TEST_ID). Ensure mic published and not muted."
exit 4
else
ok "Found testing user track(s):"
echo "$TEST_TRACKS"
fi
# 7) Confirm teacher and assessor subscriptions include testing user's track IDs
echo "7) Checking subscriptions for teacher and assessor to testing user's tracks"
SUBS=$(lk room subscriptions --room "$ROOM_NAME" --output json 2>/dev/null)
if [ $? -ne 0 ] || [ -z "$SUBS" ]; then
warn "Could not fetch structured subscriptions. Manual verification required via participant describe outputs."
else
for tid in $TEST_TRACKS; do
matches=$(echo "$SUBS" | jq -r --arg TID "$tid" '.[] | select(.trackId==$TID) | "\(.participantIdentity) -> \(.subscribedParticipantIdentity)"' 2>/dev/null)
if [ -z "$matches" ]; then
warn "No subscription entries found for track $tid. Agents may not be subscribed."
else
ok "Subscriptions for track $tid:"
echo "$matches"
fi
done
fi
# 8) Network quick-check placeholder (requires remote access/tools)
echo "8) Network check suggestion: run a network test from testing client host (packet loss/latency)."
echo "You can run browser diagnostics or tools like ping/traceroute/iperf from the testing client."
# 9) Suggested quick remediation steps (automated actions you can run manually)
echo "9) Quick remediation commands (run if you need to republish or reset):"
echo "- Republish testing user's mic track from client (no LK CLI command; use client to unpublish/publish)"
echo "- If agent input filters are suspected: inspect agent config files and restart agent instances with filters disabled."
echo "- If agent identities collide: restart agent roles with unique identities."
# 10) Isolation test: ask operator to remove one agent then retest pub/sub
echo "10) Isolation test: remove either teacher or assessor from the room and retest. This isolates concurrency vs routing issues."
echo ""
ok "Diagnostic script complete. Review printed outputs and /tmp/lk_audio_logs.txt for errors."
echo "If you want, I can output this as a JSON checklist or add automated actions to run based on findings."
Notes:
• The script uses jq for JSON parsing; ensure jq is installed where you run it.
• LK CLI output formats can vary by version; --output json is used where available.
• The script does not unpublish/publish tracks (those actions are client-side). It focuses on participant/track/subscription inspection and log filtering.
Would you like this converted into a JSON checklist the agent can iterate through, or do you want the script extended to automatically restart agent instances or alter RoomIO/RoomInput configs?modern-winter-66316
12/04/2025, 7:07 AMtall-airline-16756
12/04/2025, 7:07 AMmodern-winter-66316
12/04/2025, 7:08 AMtall-airline-16756
12/04/2025, 7:09 AM#!/usr/bin/env bash
ROOM_NAME="english-teacher-1764831468988-l5cdb0l"
TEST_ID="user-1764..."
TEACHER_ID="agent-TEACHER-ID"
ASSESSOR_ID="agent-ASSESSOR-ID"
echo "1) Participants in room:"
lk room participants --room "$ROOM_NAME"
echo; echo "2) Testing user published tracks:"
lk room participant describe --room "$ROOM_NAME" --identity "$TEST_ID" --output json | jq '.tracks[] | {trackId, kind, muted}'
TEST_TRACK=$(lk room participant describe --room "$ROOM_NAME" --identity "$TEST_ID" --output json | jq -r '.tracks[] | select(.kind=="audio") | .trackId' | head -n1)
if [ -z "$TEST_TRACK" ]; then
echo "[ERROR] No audio track found for $TEST_ID"
exit 1
fi
echo "[INFO] Found testing audio track: $TEST_TRACK"
echo; echo "3) Check agent subscriptions for track $TEST_TRACK"
for AGENT in "$TEACHER_ID" "$ASSESSOR_ID"; do
echo; echo "Agent: $AGENT"
lk room participant describe --room "$ROOM_NAME" --identity "$AGENT" --output json | jq -r --arg T "$TEST_TRACK" '
.subscriptions // [] | map(select(.trackId==$T)) | if length>0 then "SUBSCRIBED" else "NOT_SUBSCRIBED" end'
done
echo; echo "If an agent shows NOT_SUBSCRIBED, run this on that agent host (or add to agent code) to explicitly subscribe to the track:"
echo
echo " # PSEUDO-COMMAND (agent-side):"
echo " # Use your agent SDK to subscribe to remote trackId: $TEST_TRACK for participant identity $TEST_ID"
echo
echo "Example JS (agent) snippet to subscribe explicitly:"
echo ' const participant = room.getParticipant("[REMOTE_PARTICIPANT_ID]");'
echo ' const remoteTrack = participant.getTrack("[TRACK_ID]");'
echo ' await room.subscribe(remoteTrack);'
echo
echo "Alternatively, enable auto_subscribe=True in AgentSession/agent config and redeploy agents so they auto-subscribe to remote audio."
Notes:
• LK CLI cannot remotely force another client to subscribe; subscription must be done by the agent process or client. The script detects missing subscriptions and gives the exact trackId to subscribe to.
• Replace placeholders and run the script where LK CLI and jq are available.
• If you want, I can produce a ready-to-run agent-side code snippet in your agent SDK (JS/Python/go) to perform the explicit subscribe. Which SDK do you use?modern-winter-66316
12/04/2025, 7:11 AMtall-airline-16756
12/04/2025, 7:11 AM#!/usr/bin/env bash
ROOM="english-teacher-1764831468988-l5cdb0l"
TEST_ID="user-1764..."
TEACHER_ID="agent-TEACHER-ID"
ASSESSOR_ID="agent-ASSESSOR-ID"
echo "Participants:"
lk room participants --room "$ROOM"
echo; echo "Testing user tracks:"
lk room participant describe --room "$ROOM" --identity "$TEST_ID" --output json | jq '.tracks[] | {trackId, kind, muted}'
TEST_TRACK=$(lk room participant describe --room "$ROOM" --identity "$TEST_ID" --output json | jq -r '.tracks[] | select(.kind=="audio") | .trackId' | head -n1)
if [ -z "$TEST_TRACK" ]; then
echo "[ERROR] No audio track found for $TEST_ID"; exit 1
fi
echo "[INFO] Found testing audio track: $TEST_TRACK"
for AGENT in "$TEACHER_ID" "$ASSESSOR_ID"; do
echo; echo "Agent: $AGENT"
lk room participant describe --room "$ROOM" --identity "$AGENT" --output json | jq -r --arg T "$TEST_TRACK" '
(.subscriptions // []) | map(select(.trackId==$T)) | if length>0 then "SUBSCRIBED" else "NOT_SUBSCRIBED" end'
done
echo
echo "If NOT_SUBSCRIBED, run the Python agent snippet on the corresponding agent host to subscribe to track: $TEST_TRACK"
Python agent-side subscribe snippet — run in the agent process (fill your LiveKit URL/keys and participant/track IDs). This uses the LiveKit Python SDK pattern to subscribe to a specific remote audio track; adapt to your agent code structure.
# Install: pip install livekit
from livekit import Room, LiveKitConfig, Participant, TrackKind
import asyncio
LIVEKIT_URL = "wss://your-livekit-host"
API_KEY = "API_KEY"
API_SECRET = "API_SECRET"
ROOM_NAME = "english-teacher-1764831468988-l5cdb0l"
AGENT_ID = "agent-TEACHER-ID" # this agent's identity
TARGET_PARTICIPANT_ID = "user-1764..." # testing user identity
TARGET_TRACK_ID = "TR_AM6bmK9b63FJZe" # audio track id found by LK CLI
async def subscribe_to_track():
cfg = LiveKitConfig(API_KEY, API_SECRET, url=LIVEKIT_URL)
room = Room(cfg)
await room.connect(ROOM_NAME, AGENT_ID) # authenticate as agent
# wait for participants to populate
await asyncio.sleep(1)
participant = room.get_participant(TARGET_PARTICIPANT_ID)
if not participant:
print("Target participant not found in room")
await room.disconnect()
return
# Find the remote audio publication by track id
publication = None
for pub in participant.tracks:
if getattr(pub, "track_id", None) == TARGET_TRACK_ID:
publication = pub
break
if not publication:
print("Target track publication not found on participant")
await room.disconnect()
return
# Explicit subscribe (SDKs differ; if SDK exposes subscribe API from room)
try:
await room.subscribe(publication) # if subscribe is provided by your SDK version
print("Subscribed to target track:", TARGET_TRACK_ID)
except Exception as e:
print("Subscribe call failed; ensure your SDK supports explicit subscribe. Error:", e)
# Optionally log subscribed tracks
print("Current remote tracks:")
for p in room.participants.values():
for t in p.tracks:
print(p.identity, getattr(t, "track_id", None), getattr(t, "kind", None))
await asyncio.sleep(1)
await room.disconnect()
if __name__ == "__main__":
asyncio.run(subscribe_to_track())
Notes:
• LK CLI cannot force another client to subscribe; the Python snippet must run in the agent process (or be integrated into agent code) to perform the subscription.
• Replace placeholders with actual values.
• If your Python SDK version does not expose an explicit room.subscribe(publication) API, implement the agent-side behavior to enable auto_subscribe or call the SDK’s provided subscribe mechanism for remote publications.
If you want, I can produce a version specifically targeting your agent framework (livekit-agents) or adjust for your SDK version — tell me which Python LiveKit package and version you use.modern-winter-66316
12/04/2025, 7:32 AMtall-airline-16756
12/04/2025, 7:32 AMmodern-winter-66316
12/04/2025, 7:37 AMtall-airline-16756
12/04/2025, 7:37 AMdeepgram/nova-3), redeploy the agent, and then ask you to run the same test session.
Once redeployed, please:
1. Start a lesson, speak for a few seconds.
2. Capture and paste the agent log lines around:
◦ [on_enter] Remote participants: ...
◦ [on_track_published] identity=... sid=... source=MICROPHONE ...
◦ Any lines showing STT results or errors.
If the agent still doesn’t react after redeploy, paste those logs and I’ll iterate immediately.modern-winter-66316
12/04/2025, 7:38 AMtall-airline-16756
12/04/2025, 7:38 AM# patch: ensure you import whatever AgentSession/Inference config you use
# Example: when creating the AgentSession or inference config, set stt to a valid preset.
# BEFORE (invalid)
inference_config = {
"stt": "default",
# other inference settings...
}
# AFTER (valid preset)
inference_config = {
"stt": "deepgram/nova-3", # valid LiveKit Inference STT preset
# other inference settings...
}
# example usage when creating the AgentSession (adjust to your code path)
agent_session = AgentSession(
room=room,
inference=inference_config,
# ...other args...
)
B) Redeploy & quick test procedure
1. Redeploy the agent with the updated code (your usual deploy command); example CLI placeholder:
◦ bash: ./deploy-agent.sh or your CI/CD deploy step
1. Start a new lesson in the frontend (Vercel) and join as the testing user. Speak clearly for ~5–10 seconds.
2. Capture agent logs immediately after the test. In your agent host terminal run (or use your log viewer):
◦ tail -n 200 /path/to/agent.log
◦ or your platform logs command (e.g., kubectl logs -f <pod>)
1. Verify these log markers:
◦ [on_track_published] identity=... sid=... source=MICROPHONE ... (confirms mic track seen)
◦ Lines showing STT activity/results, e.g. something like: inference/stt result=... or explicit recognizer responses (no longer "invalid provider" errors)
◦ If present, ActiveSpeaker or on_speech events showing your identity.
1. If STT still fails, paste the small log snippet around the STT lines:
◦ 5–10 lines before and after any STT error or result lines.
If you want, I can produce a ready-to-run patch PR diff for the exact file if you tell me the agent file path that constructs the inference config.modern-winter-66316
12/04/2025, 7:39 AMtall-airline-16756
12/04/2025, 7:39 AMagents/english_teacher/agent.py).
Option B — code snippet
• Paste the few lines around the current inference config (the block containing "stt": "default").
Also tell me:
• Which Python package you use for the agent (e.g., livekit, livekit-agents) and its version if known.
• How you deploy the agent (script/CI, e.g., deploy-agent.sh, Dockerfile, or Kubernetes).
Send any of the above and I’ll return:
• A ready-to-apply unified diff patch for that file (with deepgram/nova-3 set), and
• Exact deploy + test commands and the log lines to check.modern-winter-66316
12/04/2025, 7:40 AMtall-airline-16756
12/04/2025, 7:41 AMinference_config dict (or similar) with "stt": "default". If your file path differs, tell me the path and I’ll produce a patch for that file.
1) Code patch (unified diff)
• Replace the stt value with deepgram/nova-3 and add a small log line to confirm the chosen STT preset at runtime.
Apply this patch to the agent source file that builds the inference config (example file: agents/english_teacher/agent.py).
--- a/agents/english_teacher/agent.py +++ b/agents/english_teacher/agent.py @@ -1,6 +1,8 @@ import logging +import sys logging = logging.getLogger(name)
def create_inference_config(...): # adjust to your function signature
• inference_config = {
• "stt": "default",
• # other inference settings...
• }
• inference_config = {
• "stt": "deepgram/nova-3", # fixed: valid LiveKit Inference STT preset
• # other inference settings...
• }
• logging.info("Inference STT preset set to: %s", inference_config["stt"])
return inference_config
2) Docker build & deploy (example)
• Update your Docker image and restart the agent container.
Build image: docker build -t my-agent:stt-fix .
Run container (example; adapt to your env/compose/k8s): docker stop my-agent || true docker rm my-agent || true docker run -d --name my-agent \ -e LIVEKIT_URL="wss://your-livekit-host" \ -e API_KEY="..." -e API_SECRET="..." \ -v /path/to/logs:/app/logs \ my-agent:stt-fix
If you use docker-compose or Kubernetes, replace the image tag and roll the deployment.
3) Quick smoke test
• Start a lesson in the frontend (Vercel) and join as the testing user. Speak clearly for ~5–10s.
4) Log checks (what to look for)
• Agent start: look for
[INFO] Inference STT preset set to: deepgram/nova-3
• Track/publish events:
[on_enter] Remote participants: ... [on_track_published] identity=... sid=... source=MICROPHONE ...
• STT activity (should no longer show invalid provider):
lines showing STT results or inference transcripts instead of "invalid provider" errors.
5) If you still see problems — capture and paste these snippets:
• The log line with "Inference STT preset set to: ..."
• 10 lines around the most recent "[on_track_published]" for your user identity and the agent.
• Any STT error lines (the exact error text).
If you want, tell me the exact agent file path (e.g., agents/english_teacher/agent.py) and I’ll generate a git-style patch you can apply directly, plus a Kubernetes manifest or docker-compose update if you use them.modern-winter-66316
12/04/2025, 8:53 AMmodern-winter-66316
12/04/2025, 8:53 AMtall-airline-16756
12/04/2025, 8:53 AMroom:<ROOM>:speaker that stores the active speaker identity and an expiration.
• When an agent wants to speak/answer:
a. Try to acquire the lock (SETNX room:<ROOM>:speaker -> agent_id) with a short TTL (e.g., 2–5s).
b. If acquired, process audio and speak. Renew TTL while speaking.
c. On finish, release the lock (DEL) or let TTL expire.
d. If not acquired, listen and defer until lock released.
Minimal Python sketch (redis + asyncio):
# requires: aioredis
import asyncio
import aioredis
ROOM_KEY = f"room:{room_name}:speaker"
TTL = 4 # seconds
async def try_acquire(redis, agent_id):
ok = await redis.set(ROOM_KEY, agent_id, exist=redis.SET_IF_NOT_EXIST, ex=TTL)
return ok
async def renew(redis, agent_id):
# only renew if still owner
cur = await redis.get(ROOM_KEY)
if cur and cur.decode() == agent_id:
await redis.expire(ROOM_KEY, TTL)
async def release(redis, agent_id):
cur = await redis.get(ROOM_KEY)
if cur and cur.decode() == agent_id:
await redis.delete(ROOM_KEY)
Option B — Synchronize start (align processing)
• Add a short barrier so both agents wait for a common “start” event before responding (use LiveKit data messages or a shared store).
• Example: when session starts, have the controller send a data message "start_ts": <server_ts_ms>. Each agent waits until local clock >= start_ts + small buffer (e.g., 20–50ms), then begin processing; this reduces relative skew.
Minimal Python sketch (LiveKit data message):
# controller sends:
start_ts = int(time.time() * 1000) + 100 # 100ms in future
room.send_data({"type":"start","ts": start_ts})
# agent on data message:
if msg['type']=='start':
wait_ms = msg['ts'] - int(time.time()*1000) + 20 # extra buffer
if wait_ms>0:
await asyncio.sleep(wait_ms/1000)
# then begin processing/responding
Quick test procedure
1. Pick option A or B and implement in both agent instances. Deploy.
2. Start a session, have testing user speak for ~5s.
3. Observe logs:
◦ For turn-taking: logs should show lock acquired/released and only one agent processing at a time.
◦ For sync-start: both agents log start time and begin within the buffer window (check timestamps).
1. If you still see >50ms skew, increase buffer (Option B) or increase TTL/handshake in Option A.
Which would you like me to produce as a ready-to-apply patch: (1) Redis-based turn-taking code + small agent changes, or (2) data-message start-sync code? Also tell me your agent control channel (Redis available or prefer in-room data messages).tall-airline-16756
12/04/2025, 8:53 AM# file: agents/common/turntaking.py
import asyncio
import aioredis
import time
REDIS_URL = "redis://localhost:6379"
LOCK_TTL = 4 # seconds
class TurnManager:
def __init__(self, room_name, agent_id):
self.room_key = f"room:{room_name}:speaker"
self.agent_id = agent_id
self.redis = None
async def connect(self):
self.redis = await aioredis.from_url(REDIS_URL)
async def try_acquire(self):
# SET key if not exists with expiry
ok = await self.redis.set(self.room_key, self.agent_id, nx=True, ex=LOCK_TTL)
return ok is True
async def renew_if_owner(self):
cur = await self.redis.get(self.room_key)
if cur and cur.decode() == self.agent_id:
await self.redis.expire(self.room_key, LOCK_TTL)
async def release(self):
cur = await self.redis.get(self.room_key)
if cur and cur.decode() == self.agent_id:
await self.redis.delete(self.room_key)
Usage in agent main flow (pseudo-integration):
# inside agent init
turn = TurnManager(room_name, agent_identity)
await turn.connect()
# before processing/responding to audio
acquired = await turn.try_acquire()
if not acquired:
# defer: wait and retry or skip
await asyncio.sleep(0.2)
return # or loop retry
# got lock -> process and speak
try:
# while processing / speaking, periodically renew
for _ in range(0, 20): # example loop while speaking
await turn.renew_if_owner()
await asyncio.sleep(0.5)
# actual processing/speak call here
finally:
await turn.release()
3) Quick deploy steps (Docker)
• Build:
docker build -t my-agent:turntaking-fix .
• Run/update container (example):
docker stop my-agent || true docker rm my-agent || true docker run -d --name my-agent \ -e REDIS_URL="redis://redis-host:6379" \ -e ROOM_NAME="english-teacher-..." \ -e AGENT_ID="cloud-english-teacher" \ my-agent:turntaking-fix
Ensure Redis is reachable from agents.
4) Smoke test
• Start lesson, join as testing user, speak for ~5s.
• Verify logs show:
◦ "acquired lock" (you can add logging around try_acquire/renew/release)
◦ only one agent processing/speaking at a time
• If you see frequent lock contention, increase LOCK_TTL to 6–8s or add a backoff retry.
5) If you prefer synchronized start instead
• I can provide the data-message barrier variant (controller sends start_ts and agents wait until start_ts + buffer). Tell me if you want that instead.
Do you want the quick PR-style diff for where to insert this in your agent repo, or should I produce the data-message variant?modern-winter-66316
12/04/2025, 8:54 AMtall-airline-16756
12/04/2025, 8:54 AMimport aioredis
import asyncio
REDIS_URL = "redis://redis:6379" # set via env in Docker
LOCK_TTL = 4 # seconds
RETRY_DELAY = 0.2 # seconds
class TurnManager:
def __init__(self, room_name, agent_id):
self.key = f"room:{room_name}:speaker"
self.agent_id = agent_id
self.redis = None
async def connect(self):
self.redis = await aioredis.from_url(REDIS_URL)
async def try_acquire(self):
return await self.redis.set(self.key, self.agent_id, nx=True, ex=LOCK_TTL)
async def wait_and_acquire(self, timeout=5.0):
end = asyncio.get_event_loop().time() + timeout
while asyncio.get_event_loop().time() < end:
ok = await self.try_acquire()
if ok:
return True
await asyncio.sleep(RETRY_DELAY)
return False
async def renew_if_owner(self):
cur = await self.redis.get(self.key)
if cur and cur.decode() == self.agent_id:
await self.redis.expire(self.key, LOCK_TTL)
async def release(self):
cur = await self.redis.get(self.key)
if cur and cur.decode() == self.agent_id:
await self.redis.delete(self.key)
2) Integration (wrap agent processing/speaking logic)
• Import and initialize TurnManager at agent start:
turn = TurnManager(room_name, agent_identity)
await turn.connect()
• Before processing/responding to audio, attempt to acquire:
got = await turn.wait_and_acquire(timeout=2.0)
if not got:
# defer: skip or retry later
return
try:
# while processing/speaking, periodically renew lock
async def renew_loop():
while True:
await asyncio.sleep(LOCK_TTL / 2)
await turn.renew_if_owner()
renew_task = asyncio.create_task(renew_loop())
# perform your normal processing and TTS/speaking here
finally:
renew_task.cancel()
await turn.release()
3) Docker / env
• Ensure Redis is reachable; set REDIS_URL accordingly (e.g., docker-compose service name).
• Rebuild image and redeploy both agent containers:
docker build -t my-agent:turnfix . docker run -d --name agent1 -e REDIS_URL="redis://redis:6379" ... my-agent:turnfix docker run -d --name agent2 -e REDIS_URL="redis://redis:6379" ... my-agent:turnfix
4) Quick test checklist
• Start a session, have test user speak ~5s.
• Confirm logs show one agent acquiring the lock, processing, then releasing; the other agent should not process concurrently.
• If frequent contention occurs, increase LOCK_TTL to 6–8s or adjust retry timeout/backoff.
If you want, I can produce a small PR diff that inserts this into your agent file — tell me the agent file path and I’ll generate it.modern-winter-66316
12/04/2025, 8:57 AMtall-airline-16756
12/04/2025, 8:57 AM# where you construct inference config / AgentSession
inference_config = {
"stt": "deepgram/nova-3",
"conversation_mode": "turn_based", # ensure turn-based behavior
# optional tuning:
"turn_timeout_s": 4, # how long a turn lasts
"turn_grace_s": 0.5, # small overlap allowance
}
agent_session = AgentSession(room=room, inference=inference_config, ...)
2) Add a small log to confirm:
logging.info("Inference conversation_mode=%s turn_timeout=%s", inference_config["conversation_mode"], inference_config["turn_timeout_s"])
3) Redeploy agent (lk agent deploy) and test:
• Deploy: lk agent deploy --name cloud-english-teacher
• Start lesson, speak for ~5–10s.
• Check agent logs for:
◦ "Inference conversation_mode=turn_based" log line
◦ on_track_published lines for your mic
◦ logs showing agent taking/ending turns (look for phrases like "start_turn"/"end_turn" or STT-triggered actions)
4) If you want a slightly more responsive flow, tweak:
• Decrease turn_timeout_s to shorten turn length.
• Increase turn_grace_s to allow small overlaps without stepping on speech.
If your agent SDK version does not accept conversation_mode in the inference config, tell me the agent file that creates AgentSession and I’ll produce the exact patch for that code.modern-winter-66316
12/04/2025, 9:06 AMtall-airline-16756
12/04/2025, 9:07 AMstart_session_timeout(ctx, room, MAX_SECONDS) after you create/connect the AgentSession.
# agents/english_teacher/session_timeout.py
import asyncio
import logging
logger = logging.getLogger(__name__)
def start_session_timeout(ctx, room, max_seconds=1800):
"""
Start a background task that enforces a maximum session duration.
Cancels itself if the session ends normally.
- ctx: job context that supports add_shutdown_callback (JobContext-like)
- room: agent's Room/AgentSession object with a `disconnect()` or `shutdown()` coroutine
- max_seconds: maximum allowed session duration in seconds
"""
async def _watcher():
try:
logger.info("Session timeout watcher started: max_seconds=%s", max_seconds)
await asyncio.sleep(max_seconds)
logger.info("Max session duration reached (%s s). Ending session.", max_seconds)
try:
# prefer graceful disconnect/shutdown APIs on your session/room
if hasattr(room, "disconnect"):
await room.disconnect()
elif hasattr(room, "shutdown"):
await room.shutdown()
elif hasattr(room, "close"):
await room.close()
else:
logger.warning("No known shutdown method on room object; skipping disconnect.")
except Exception as e:
logger.exception("Error while ending session due to timeout: %s", e)
# Optionally signal job shutdown if ctx exposes it
try:
if hasattr(ctx, "shutdown"):
await ctx.shutdown()
except Exception:
# ctx.shutdown may be sync or not present
pass
except asyncio.CancelledError:
logger.info("Session timeout watcher cancelled (session ended normally).")
except Exception:
logger.exception("Session timeout watcher error")
task = asyncio.create_task(_watcher())
# ensure the watcher is cancelled when job/session ends
def _on_shutdown():
if not task.done():
task.cancel()
if hasattr(ctx, "add_shutdown_callback"):
ctx.add_shutdown_callback(_on_shutdown)
else:
# fallback: if ctx supports on/started hooks, attach appropriate callback
try:
ctx.on("shutdown", _on_shutdown)
except Exception:
logger.warning("Could not register shutdown callback for session timeout watcher")
return task
2) How to integrate (example)
• After you create/connect the AgentSession/room in your entrypoint, call:
from agents.english_teacher.session_timeout import start_session_timeout
MAX_SESSION_SECONDS = 1800 # 30 minutes, adjust as needed
timeout_task = start_session_timeout(ctx, room, MAX_SESSION_SECONDS)
• Ensure the room object you pass exposes disconnect() or shutdown() (adjust calls in watcher to match your AgentSession API).
3) Docker redeploy
• Rebuild image:
docker build -t my-agent:session-timeout-1 .
• Redeploy agent (for LiveKit Cloud managed agent, use your usual deploy flow; if using lk agent deploy, update the container image or code and run):
lk agent deploy --name cloud-english-teacher
• If you run locally:
docker run -d --name my-agent ... my-agent:session-timeout-1
4) Test checklist
• Start a session and note start time.
• Wait the configured timeout (or set MAX_SESSION_SECONDS small, e.g., 60s, for quick test).
• Confirm agent logs show:
◦ "Session timeout watcher started: max_seconds=..."
◦ "Max session duration reached (... s). Ending session."
◦ Successful room disconnect/shutdown lines (no unhandled exceptions).
• Verify session in your dashboard moves to CLOSED after the agent disconnects.
5) Notes and tuning
• Set MAX_SESSION_SECONDS to your desired policy (e.g., 1800 for 30m, 3600 for 1h).
• This is a graceful stop; if you need forceful termination, add a secondary forced-kill after a brief grace period.
• Combine with analytics/logging to detect why sessions exceed expected durations (e.g., client never leaves, job stuck, or speech-detection failures).
If you want, I can:
• Produce a git-style unified diff for the exact agent file path if you tell me where to insert this, or
• Change the default timeout to 1 hour and add an admin override via env var (e.g., SESSION_MAX_SECONDS). Which would you prefer? Sources: Job lifecycle | LiveKit docs | How to detect and handle silence during calls | Analytics API | LiveKit docs | Deploy and scale agents on LiveKit Cloudmodern-winter-66316
12/04/2025, 9:08 AMtall-airline-16756
12/04/2025, 9:09 AMallow_interruptions=False
◦ min speech threshold ≈ 1s
◦ VAD silence ≈ 4s
2) What this will do
• Reduce agent cutting in mid-sentence and shorten perceived overlap.
• Makes turns more distinct without adding external infra (no Redis).
3) Test checklist (short)
• Start a lesson, speak for several turns, and listen for:
◦ Agent waits for you to finish before replying.
◦ Fewer partial/overlapping agent responses.
• Capture agent logs for 1–2 short conversations and paste lines showing:
◦ agent turn start/end or VAD events
◦ any interruption attempts
4) If overlap still noticeable, two safe tweaks to try
• Increase min speech threshold to 1.5–2s to avoid very short triggers.
• Increase VAD silence to 5–6s so the agent waits longer before ending its turn.
5) Session duration reminder
• If you want the session timeout applied too, I can provide the small session-timeout patch (runs inside the agent, uses ctx + room.disconnect()) and a git-style diff. Do you want that?modern-winter-66316
12/04/2025, 9:10 AMmodern-winter-66316
12/04/2025, 9:10 AMtall-airline-16756
12/04/2025, 9:11 AM*** Begin Patch: enable turn-based-safe settings + session timeout watcher ***
*** File: cloud-agent/agent/main.py
@@
-# existing imports...
+import asyncio
+import logging
+import os
@@
-from livekit.agents import AgentSession, JobContext
+from livekit.agents import AgentSession, JobContext
@@
def start_job(ctx: JobContext):
# existing job setup...
- inference_cfg = {
- "stt": "deepgram/nova-3",
- # other inference settings...
- }
- agent_session = AgentSession(room=room, inference=inference_cfg, ...)
+ # --- Turn-based safe inference config (SDK-supported fields) ---
+ inference_cfg = {
+ "stt": "deepgram/nova-3",
+ # Prevent agent from interrupting itself and reduce overlap
+ "allow_interruptions": False, # disable self-interruptions
+ "min_speech_seconds_before_interrupt": 1.0, # require ~1s of speech to consider interrupt
+ "max_vad_silence_seconds": 4.0, # allow up to ~4s of VAD silence before ending a turn
+ # other inference settings...
+ }
+ logging.info("Inference config: stt=%s allow_interruptions=%s min_speech_s=%s max_vad_s=%s",
+ inference_cfg["stt"],
+ inference_cfg["allow_interruptions"],
+ inference_cfg["min_speech_seconds_before_interrupt"],
+ inference_cfg["max_vad_silence_seconds"])
+
+ agent_session = AgentSession(room=room, inference=inference_cfg, ...)
@@
# start the agent session normally
- await agent_session.start()
+ await agent_session.start()
+
+ # --- Session timeout watcher: enforce max session duration ---
+ from agents.common.session_timeout import start_session_timeout
+ # configurable via env var, default 3600s (1 hour)
+ MAX_SESSION_SECONDS = int(os.getenv("SESSION_MAX_SECONDS", "3600"))
+ timeout_task = start_session_timeout(ctx, room, MAX_SESSION_SECONDS)
+
+ # ensure normal shutdown cancels watcher (start_session_timeout registers callback)
+ # existing job main loop / processing continues...
*** End Patch ***
*** New File: agents/common/session_timeout.py
+import asyncio
+import logging
+
+logger = logging.getLogger(__name__)
+
+def start_session_timeout(ctx, room, max_seconds=3600):
+ """
+ Start background watcher that enforces a maximum session duration.
+ - ctx: JobContext-like object (should support add_shutdown_callback or on("shutdown"))
+ - room: AgentSession/Room object exposing disconnect()/shutdown()/close()
+ - max_seconds: maximum allowed session duration in seconds
+ """
+ async def _watcher():
+ try:
+ logger.info("Session timeout watcher started: max_seconds=%s", max_seconds)
+ await asyncio.sleep(max_seconds)
+ logger.info("Max session duration reached (%s s). Ending session.", max_seconds)
+ try:
+ if hasattr(room, "disconnect"):
+ await room.disconnect()
+ elif hasattr(room, "shutdown"):
+ await room.shutdown()
+ elif hasattr(room, "close"):
+ await room.close()
+ else:
+ logger.warning("No known shutdown method on room object; skipping disconnect.")
+ except Exception as e:
+ logger.exception("Error while ending session due to timeout: %s", e)
+ try:
+ if hasattr(ctx, "shutdown"):
+ # prefer async shutdown if available
+ maybe = ctx.shutdown
+ if asyncio.iscoroutinefunction(maybe):
+ await maybe()
+ else:
+ # call sync shutdown if present
+ maybe()
+ except Exception:
+ pass
+ except asyncio.CancelledError:
+ logger.info("Session timeout watcher cancelled (session ended normally).")
+ except Exception:
+ logger.exception("Session timeout watcher error")
+
+ task = asyncio.create_task(_watcher())
+
+ def _on_shutdown():
+ if not task.done():
+ task.cancel()
+
+ # Register shutdown callback if available
+ try:
+ if hasattr(ctx, "add_shutdown_callback"):
+ ctx.add_shutdown_callback(_on_shutdown)
+ elif hasattr(ctx, "on"):
+ ctx.on("shutdown", _on_shutdown)
+ else:
+ logger.warning("JobContext does not support shutdown callbacks; timeout watcher may persist.")
+ except Exception:
+ logger.exception("Failed to register session timeout shutdown callback")
+
+ return task
+
*** End Patch ***
Rebuild & redeploy (example)
1. Bump image, build, and push:
◦ docker build -t my-agent:turn-timeout-fix .
◦ docker push my-agent:turn-timeout-fix
1. Deploy to LiveKit Cloud (your usual flow):
◦ lk agent deploy --name cloud-english-teacher
◦ or follow your CI pipeline to replace the agent image
Quick test checklist
1. Start a lesson, speak for several turns. Confirm agent waits to finish before replying (less overlap).
2. Verify logs contain:
◦ "Inference config: stt=deepgram/nova-3 allow_interruptions=False ..." line
◦ Session timeout watcher start: "Session timeout watcher started: max_seconds=..."
◦ If session exceeds max, "Max session duration reached (...) Ending session."
1. Tuning:
◦ Adjust SESSION_MAX_SECONDS env var to desired max (e.g., 1800 for 30m).
◦ If overlap remains, increase min_speech_seconds_before_interrupt to 1.5–2.0 or max_vad_silence_seconds to 5–6.
If you want, I’ll produce a git-style patch file you can apply directly to your repository or adjust the exact AgentSession call signature if you share the real snippet from cloud-agent/agent/main.py.tall-airline-16756
12/04/2025, 9:11 AM*** Begin Patch: enable turn-safe inference + session timeout watcher ***
*** File: cloud-agent/agent/main.py
@@
import asyncio
import logging
import os
@@
-from livekit.agents import AgentSession, JobContext
+from livekit.agents import AgentSession, JobContext
@@
def start_job(ctx: JobContext):
# existing job setup...
- inference_cfg = {
- "stt": "deepgram/nova-3",
- # other inference settings...
- }
- agent_session = AgentSession(room=room, inference=inference_cfg, ...)
+ # --- Turn-safe inference config (SDK-supported fields) ---
+ inference_cfg = {
+ "stt": "deepgram/nova-3",
+ # Disable self-interruptions and tune thresholds to reduce overlap
+ "allow_interruptions": False,
+ "min_speech_seconds_before_interrupt": 1.0,
+ "max_vad_silence_seconds": 4.0,
+ # other inference settings...
+ }
+ logging.info("Inference config: stt=%s allow_interruptions=%s min_speech_s=%s max_vad_s=%s",
+ inference_cfg["stt"],
+ inference_cfg["allow_interruptions"],
+ inference_cfg["min_speech_seconds_before_interrupt"],
+ inference_cfg["max_vad_silence_seconds"])
+
+ agent_session = AgentSession(room=room, inference=inference_cfg, ...)
@@
- await agent_session.start()
+ await agent_session.start()
+
+ # --- Session timeout watcher: enforce max session duration ---
+ from agents.common.session_timeout import start_session_timeout
+ MAX_SESSION_SECONDS = int(os.getenv("SESSION_MAX_SECONDS", "3600")) # default 1 hour
+ timeout_task = start_session_timeout(ctx, room, MAX_SESSION_SECONDS)
+
+ # rest of job/process continues...
*** End Patch ***
*** New File: agents/common/session_timeout.py
+import asyncio
+import logging
+
+logger = logging.getLogger(__name__)
+
+def start_session_timeout(ctx, room, max_seconds=3600):
+ """
+ Background watcher that enforces a maximum session duration.
+ - ctx: JobContext-like object (supports add_shutdown_callback or on)
+ - room: AgentSession/Room exposing disconnect()/shutdown()/close()
+ - max_seconds: seconds before forced graceful disconnect
+ """
+ async def _watcher():
+ try:
+ logger.info("Session timeout watcher started: max_seconds=%s", max_seconds)
+ await asyncio.sleep(max_seconds)
+ logger.info("Max session duration reached (%s s). Ending session.", max_seconds)
+ try:
+ if hasattr(room, "disconnect"):
+ await room.disconnect()
+ elif hasattr(room, "shutdown"):
+ await room.shutdown()
+ elif hasattr(room, "close"):
+ await room.close()
+ else:
+ logger.warning("No known shutdown method on room object; skipping disconnect.")
+ except Exception as e:
+ logger.exception("Error while ending session due to timeout: %s", e)
+ try:
+ if hasattr(ctx, "shutdown"):
+ maybe = ctx.shutdown
+ if asyncio.iscoroutinefunction(maybe):
+ await maybe()
+ else:
+ maybe()
+ except Exception:
+ pass
+ except asyncio.CancelledError:
+ logger.info("Session timeout watcher cancelled (session ended normally).")
+ except Exception:
+ logger.exception("Session timeout watcher error")
+
+ task = asyncio.create_task(_watcher())
+
+ def _on_shutdown():
+ if not task.done():
+ task.cancel()
+
+ try:
+ if hasattr(ctx, "add_shutdown_callback"):
+ ctx.add_shutdown_callback(_on_shutdown)
+ elif hasattr(ctx, "on"):
+ ctx.on("shutdown", _on_shutdown)
+ else:
+ logger.warning("JobContext does not support shutdown callbacks; timeout watcher may persist.")
+ except Exception:
+ logger.exception("Failed to register session timeout shutdown callback")
+
+ return task
+
*** End Patch ***
Rebuild & deploy
• Build image:
docker build -t my-agent:turn-timeout-fix .
• Push/update your registry if used.
• Deploy to LiveKit Cloud (your usual flow):
lk agent deploy --name cloud-english-teacher
• Or use your CI to replace the agent image.
Quick test
1. Start a lesson, speak several turns. Confirm agent waits and overlap is reduced.
2. For timeout test, set a short SESSION_MAX_SECONDS locally (e.g., export SESSION_MAX_SECONDS=60) before deploying, start a session, and confirm logs:
◦ "Inference config: stt=deepgram/nova-3 allow_interruptions=False ..."
◦ "Session timeout watcher started: max_seconds=60"
◦ After timeout: "Max session duration reached (...) Ending session." and agent disconnect/shutdown logs.
1. Tune:
◦ Increase min_speech_seconds_before_interrupt (1.5–2.0) if short triggers still happen.
◦ Increase max_vad_silence_seconds (5–6) to wait longer before ending turns.
◦ Set SESSION_MAX_SECONDS to your desired policy (e.g., 1800 for 30m).
If you want, I’ll:
• Produce a git-style patch file you can apply directly, or
• Adjust the exact AgentSession call signature if you paste the current snippet from cloud-agent/agent/main.py. Which would you prefer?modern-winter-66316
12/04/2025, 6:28 PMtall-airline-16756
12/04/2025, 6:28 PMgit apply apply_fix.patch. It updates cloud-agent/agent/main.py to enable SDK-supported turn-safe inference settings and adds agents/common/session_timeout.py implementing the session timeout watcher. After applying, rebuild and redeploy your agent image.
Save as apply_fix.patch:
* Begin Patch * Add File: agents/common/session_timeout.py +import asyncio +import logging + +logger = logging.getLogger(name) + +def start_session_timeout(ctx, room, max_seconds=3600):
• """
• Background watcher that enforces a maximum session duration.
• - ctx: JobContext-like object (supports add_shutdown_callback or on)
• - room: AgentSession/Room exposing disconnect()/shutdown()/close()
• - max_seconds: seconds before graceful disconnect
• """
• async def _watcher():
• try:
• logger.info("Session timeout watcher started: max_seconds=%s", max_seconds)
• await asyncio.sleep(max_seconds)
• logger.info("Max session duration reached (%s s). Ending session.", max_seconds)
• try:
• if hasattr(room, "disconnect"):
• await room.disconnect()
• elif hasattr(room, "shutdown"):
• await room.shutdown()
• elif hasattr(room, "close"):
• await room.close()
• else:
• logger.warning("No known shutdown method on room object; skipping disconnect.")
• except Exception as e:
• logger.exception("Error while ending session due to timeout: %s", e)
• try:
• if hasattr(ctx, "shutdown"):
• maybe = ctx.shutdown
• if asyncio.iscoroutinefunction(maybe):
• await maybe()
• else:
• maybe()
• except Exception:
• pass
• except asyncio.CancelledError:
• logger.info("Session timeout watcher cancelled (session ended normally).")
• except Exception:
• logger.exception("Session timeout watcher error")
+
• task = asyncio.create_task(_watcher())
+
• def _on_shutdown():
• if not task.done():
• task.cancel()
+
• try:
• if hasattr(ctx, "add_shutdown_callback"):
• ctx.add_shutdown_callback(_on_shutdown)
• elif hasattr(ctx, "on"):
• ctx.on("shutdown", _on_shutdown)
• else:
• logger.warning("JobContext does not support shutdown callbacks; timeout watcher may persist.")
• except Exception:
• logger.exception("Failed to register session timeout shutdown callback")
+
• return task
+ * End Patch
* Begin Patch * Update File: cloud-agent/agent/main.py @@ -import asyncio -import logging -import os +import asyncio +import logging +import os @@ -from livekit.agents import AgentSession, JobContext +from livekit.agents import AgentSession, JobContext @@ def start_job(ctx: JobContext):
• # existing job setup...
• inference_cfg = {
• "stt": "deepgram/nova-3",
• # other inference settings...
• }
• agent_session = AgentSession(room=room, inference=inference_cfg, ...)
• # existing job setup...
• # --- Turn-safe inference config (SDK-supported fields) ---
• inference_cfg = {
• "stt": "deepgram/nova-3",
• # Disable self-interruptions and tune thresholds to reduce overlap
• "allow_interruptions": False,
• "min_speech_seconds_before_interrupt": 1.0,
• "max_vad_silence_seconds": 4.0,
• # other inference settings...
• }
• logging.info(
• "Inference config: stt=%s allow_interruptions=%s min_speech_s=%s max_vad_s=%s",
• inference_cfg["stt"],
• inference_cfg["allow_interruptions"],
• inference_cfg["min_speech_seconds_before_interrupt"],
• inference_cfg["max_vad_silence_seconds"],
• )
+
• agent_session = AgentSession(room=room, inference=inference_cfg, ...)
@@
• await agent_session.start()
• await agent_session.start()
+
• # --- Session timeout watcher: enforce max session duration ---
• from agents.common.session_timeout import start_session_timeout
• MAX_SESSION_SECONDS = int(os.getenv("SESSION_MAX_SECONDS", "3600")) # default 1 hour
• timeout_task = start_session_timeout(ctx, room, MAX_SESSION_SECONDS)
+
• # rest of job/process continues...
* End Patch
Instructions after applying the patch
1. Apply:
git apply apply_fix.patch
1. Rebuild image:
docker build -t my-agent:turn-timeout-fix .
1. Push/update registry if used.
2. Redeploy agent to LiveKit Cloud (your usual flow), e.g.:
lk agent deploy --name cloud-english-teacher
Quick tests
• Verify logs show:
◦ "Inference config: stt=deepgram/nova-3 allow_interruptions=False ..."
◦ "Session timeout watcher started: max_seconds=..."
◦ When timeout reached: "Max session duration reached (...). Ending session." and graceful disconnect.
• For quick validation, set SESSION_MAX_SECONDS=60 before deploy to test the watcher.
If you want, I can:
• Convert this into a git commit patch (git format-patch) or produce the exact edit if you paste the current contents of cloud-agent/agent/main.py so the AgentSession call is filled precisely. Which do you prefer?