brief-evening-79958
12/03/2025, 5:06 AMtall-airline-16756
12/03/2025, 5:06 AMtall-airline-16756
12/03/2025, 5:07 AMSIP participant (kind=SIP) in the room?
3. Which SIP trunk are you using — a third‑party inbound trunk or LiveKit Phone Numbers? Any trunk config details (SIP URI, transport TCP/UDP) you can share.
4. Does the agent appear connected to the same LiveKit room as MicroSIP (room events/logs show agent join)?
5. Is TTS enabled for the agent session and are you calling session.say() or generate_reply() after user input?
6. How do you trigger the agent reply (VAD, DTMF, participant join, or other event)?
7. Any error messages or warnings from the agent logs, LiveKit room events, or MicroSIP console?
If you prefer, paste relevant log snippets (agent logs and room events) or a brief description of the call flow and SIP URI format you’re using. With that I’ll suggest targeted fixes for dispatch, media routing, TTS publishing, or SIP signaling.
Sources: SIP APIs | LiveKit docs | sip | livekit/livekit_composite | DeepWiki | Accepting inbound calls | LiveKit docs | livekit/livekit_composite | DeepWiki | Agent speech and audio | LiveKit docsbrief-evening-79958
12/03/2025, 5:07 AMtall-airline-16756
12/03/2025, 5:07 AMMultilingualModel lives in the multilingual submodule, not at the package top level. Fix the import and ensure the turn-detector plugin and model files are installed.
Do this:
1. Replace the incorrect import:
from livekit.plugins.turn_detector.multilingual import MultilingualModel
1. Install the turn-detector plugin (if not already):
• If using uv: uv add "livekit-agents[turn-detector]~=1.2"
• Or with pip: pip install "livekit-plugins-turn-detector>=1.2"
1. Download the model weights before running the agent:
• Run your script/CLI in download-files mode, e.g.:
uv run app/agents/openai_agent.py download-files
After those steps, rerun your agent. If the agent still doesn't respond via MicroSIP, share:
• Any new errors or logs after fixing the import
• Whether OpenAI Realtime TTS/STT is connecting (OPENAI_API_KEY set)
• Room and SIP connection events (agent join, participant kind=SIP)
I can then suggest targeted checks for TTS publishing, dispatch, and SIP/media routing.
Sources: LiveKit turn detector plugin | LiveKit docs | Improving voice AI's turn detection with transformers | Turn detection and interruptions | LiveKit Docsbrief-evening-79958
12/03/2025, 5:08 AMtall-airline-16756
12/03/2025, 5:09 AMMultilingualModel. Keep your environment, dependencies, and model files installed as discussed earlier.
import os
import asyncio
import logging
from dotenv import load_dotenv
import asyncpg
from datetime import datetime
from livekit import agents, rtc
from livekit.agents import AgentServer, AgentSession, JobContext, Agent
from livekit.plugins import openai, silero, noise_cancellation
from livekit.plugins.turn_detector.multilingual import MultilingualModel # fixed import
load_dotenv(".env.local")
# Config
AGENT_NAME = "AgnoX-AI-Agent"
GREETING = "Hello, this is AgnoX. How can I help you today?"
DATABASE_URL = os.getenv("DATABASE_URL")
OPENAI_VOICE = "alloy"
LOG = logging.getLogger("realtime_agent_db")
logging.basicConfig(level=logging.INFO)
server = AgentServer()
class AgnoXAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a friendly customer service voice assistant. Respond concisely and helpfully."
)
# DB helpers
async def create_db_pool():
if not DATABASE_URL:
raise RuntimeError("DATABASE_URL not set in environment")
return await asyncpg.create_pool(DATABASE_URL, min_size=1, max_size=5)
async def create_call_session(conn, room_name, caller=None, customer_id=None, agent_id=None, handled_by="ai", call_metadata=None):
row = await conn.fetchrow(
"""
INSERT INTO call_sessions (customer_id, agent_id, room_name, start_time, handled_by, call_metadata)
VALUES ($1, $2, $3, NOW(), $4, $5)
RETURNING session_id
""",
customer_id, agent_id, room_name, handled_by, call_metadata or {}
)
return row["session_id"]
async def close_call_session(conn, session_id, end_time=None, duration_seconds=None, handled_by=None, sentiment=None):
await conn.execute(
"""
UPDATE call_sessions
SET end_time = $1,
duration_seconds = $2,
handled_by = COALESCE($3, handled_by),
sentiment = COALESCE($4, sentiment)
WHERE session_id = $5
""",
end_time or datetime.utcnow(), duration_seconds, handled_by, sentiment, session_id
)
async def insert_transcript(conn, session_id, speaker, text, confidence=1.0, sentiment=None):
await conn.execute(
"""
INSERT INTO transcripts(session_id, speaker, text, confidence, sentiment)
VALUES ($1, $2, $3, $4, $5)
""",
session_id, speaker, text, float(confidence), sentiment
)
@server.rtc_session(agent_name=AGENT_NAME)
async def realtime_agent(ctx: JobContext):
pool = await create_db_pool()
# Build OpenAI Realtime model (handles STT + TTS)
realtime_model = openai.realtime.RealtimeModel(
voice=OPENAI_VOICE,
temperature=0.5,
modalities=["audio"],
)
session = AgentSession(
llm=realtime_model,
vad=silero.VAD.load(),
turn_detection=MultilingualModel(),
)
room_options = rtc.RoomOptions(close_on_disconnect=False)
async def telephony_noise(params):
if params.participant and params.participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP:
return noise_cancellation.BVCTelephony()
return noise_cancellation.BVC()
# Infer room name
try:
room_name = ctx.room.name if hasattr(ctx.room, "name") else str(ctx.room)
except Exception:
room_name = str(ctx.room)
customer_id = None
agent_id = None
async with pool.acquire() as conn:
try:
ctx.session_id = await create_call_session(conn, room_name, caller=None, customer_id=customer_id, agent_id=agent_id)
LOG.info("Created call_sessions entry id=%s for room=%s", ctx.session_id, room_name)
except Exception as e:
LOG.exception("Failed to create call_sessions row: %s", e)
ctx.session_id = None
# Handlers for transcripts and agent replies
async def handle_transcript(participant, transcript_text, is_final, confidence=1.0):
speaker = str(participant) if participant is not None else "caller"
tag = "FINAL" if is_final else "PARTIAL"
LOG.info("[TRANSCRIPT][%s] speaker=%s: %s", tag, speaker, transcript_text)
try:
async with pool.acquire() as conn:
await insert_transcript(conn, ctx.session_id, speaker, transcript_text, confidence, None)
except Exception as e:
LOG.exception("DB insert failed for transcript: %s", e)
async def handle_agent_reply(speech_text, speech_id=None):
LOG.info("[AGENT_REPLY] %s (speech_id=%s)", speech_text, speech_id)
try:
async with pool.acquire() as conn:
await insert_transcript(conn, ctx.session_id, "agent", speech_text, 1.0, None)
except Exception as e:
LOG.exception("DB insert failed for agent reply: %s", e)
# Start the session bound to the current room and agent instance
await session.start(
room=ctx.room,
agent=AgnoXAgent(),
room_options=room_options,
room_input_options=rtc.RoomInputOptions(noise_cancellation=telephony_noise),
)
# Register event callbacks (SDK may differ; adjust if needed)
try:
session.on("transcript", handle_transcript)
except Exception:
LOG.debug("session.on('transcript') not available; transcripts may still appear via other hooks")
try:
session.on("agent_speech", handle_agent_reply)
except Exception:
LOG.debug("session.on('agent_speech') not available; agent replies may still appear via other hooks")
start_time = datetime.utcnow()
try:
await asyncio.sleep(1.0)
await session.generate_reply(instructions=f"Say: '{GREETING}' in a warm, natural tone.")
await session.wait_closed()
LOG.info("Agent session closed normally")
except Exception as e:
LOG.exception("Agent session error: %s", e)
finally:
end_time = datetime.utcnow()
duration = int((end_time - start_time).total_seconds())
try:
async with pool.acquire() as conn:
if getattr(ctx, "session_id", None):
await close_call_session(conn, ctx.session_id, end_time=end_time, duration_seconds=duration, handled_by="ai")
LOG.info("Updated call_sessions id=%s with duration=%s", ctx.session_id, duration)
except Exception as e:
LOG.exception("Failed to update call_sessions: %s", e)
try:
await session.close()
except Exception:
pass
try:
await pool.close()
except Exception:
pass
if __name__ == "__main__":
agents.cli.run_app(server)
Notes:
• Ensure you installed the turn-detector plugin and downloaded model weights:
◦ Install: pip or uv install of the turn-detector extra
◦ Download weights: run your script with the CLI download-files mode (e.g., uv run app/agents/openai_agent.py download-files)
• Verify environment variables: DATABASE_URL, OPENAI_API_KEY, and any LiveKit credentials required by your deployment.
• If you still see issues after this change, paste the new traceback or relevant logs and I’ll guide the next steps (TTS publish, SIP participant kind, or OpenAI Realtime connectivity).brief-evening-79958
12/03/2025, 5:10 AMtall-airline-16756
12/03/2025, 5:10 AMDATABASE_URL, OPENAI_API_KEY, and any LiveKit credentials are set in .env.local.
• Install extras:
◦ pip install "livekit-plugins-turn-detector>=1.2" (or use your package tool).
◦ Ensure livekit-agents and livekit-plugins-noise-cancellation are installed.
• Download model weights:
◦ Run your agent CLI in download-files mode (example):
uv run app/agents/openai_agent.py download-files
• Verify Python virtualenv active and packages import without error:
◦ python -c "import livekit.plugins.turn_detector.multilingual; print('ok')"
2) Start LiveKit room and agent
• Start your LiveKit server (or ensure hosted LiveKit is reachable).
• Start your agent process with your script in development mode:
◦ python app/agents/openai_agent.py dev
• Confirm agent process logs show successful initialization and model load (no ImportError, no missing-weights messages).
3) Connect MicroSIP to LiveKit via SIP
• Configure MicroSIP SIP account to use LiveKit SIP endpoint and DID: [did]@[LiveKit_SIP_endpoint], correct username/password and transport (TCP/UDP) per your trunk.
• Place MicroSIP call into the LiveKit room (call the DID).
• In MicroSIP, confirm call is established (audio RTP stream active).
4) Validate participant join and kind
• Check LiveKit room logs / agent logs that show:
◦ Participant join event
◦ Participant kind indicates SIP (or ParticipantKind.PARTICIPANT_KIND_SIP)
• If participant kind is not SIP, verify SIP trunk config and SIP URI format.
5) Verify audio capture (caller → agent)
• Speak into MicroSIP and watch agent logs:
◦ Transcript callbacks should log partial/final transcripts (handle_transcript).
◦ If transcripts do not appear, check STT plugin (OpenAI Realtime) connectivity and that audio packets are reaching the room (network/NAT).
• If no transcripts: enable verbose logs and inspect RTP/media stats and room events.
6) Trigger agent reply (agent → MicroSIP)
• Your script calls session.generate_reply(...) to make the agent speak the GREETING. After agent started and MicroSIP call is active:
◦ Confirm agent logs show agent reply / agent_speech handler invoked.
◦ In MicroSIP you should hear TTS audio from the agent.
• If no audio arrives:
◦ Confirm OpenAI Realtime TTS is enabled and your realtime_model has modalities=["audio"].
◦ Check that the agent publishes audio tracks into the same room and that LiveKit is forwarding them to SIP trunk.
◦ Inspect agent logs for TTS errors or publish failures.
7) Verify DB transcript and call session entries
• After a short test call, check call_sessions row exists and transcripts rows were inserted for caller and agent speech.
• If DB inserts failed, check connection string and pool errors in logs.
8) Common debugging checks
• If agent never replies but transcripts exist:
◦ Confirm session.generate_reply() returns without error and AgentSession publishes TTS.
◦ Try calling await session.say("test") or await session.generate_reply(instructions="Say: hello") manually from a minimal script to isolate.
• If SIP media not forwarding:
◦ Verify SIP trunk configuration and LiveKit SIP gateway; check for NAT/firewall blocking RTP.
• If Realtime model fails to connect:
◦ Check OPENAI_API_KEY and Realtime quotas, verify network egress to OpenAI endpoints.
9) Smoke test checklist (pass/fail)
• [ ] Agent process starts with no import/model errors
• [ ] MicroSIP connects and call is established to LiveKit DID
• [ ] Room shows SIP participant kind
• [ ] Agent receives transcript entries when speaking
• [ ] Agent emits TTS and MicroSIP hears GREETING
• [ ] DB shows call_sessions + transcripts for the call
10) If you hit a failing step — what to capture and share here
• Agent process logs (full traceback if any).
• Room join events showing participant kind.
• Transcript log lines and agent_speech log lines.
• MicroSIP console/trace showing RTP or SIP setup (INVITE/200 OK).
• Any Realtime API error lines.
Tell me which test step fails and paste the relevant logs/snippets and I’ll help troubleshoot the exact cause.brief-evening-79958
12/03/2025, 5:12 AMtall-airline-16756
12/03/2025, 5:13 AM