the ai agent is not responding via microsip the au...
# ask-ai
b
the ai agent is not responding via microsip the audio has capturen by livekit
t
Thanks for reaching out, Vishnu. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’m responding to your note that the AI agent isn’t replying in MicroSIP even though LiveKit is capturing audio. I can help troubleshoot, but I need a few details to pinpoint the problem. Please provide: 1. How the agent is dispatched to the room — are you using an explicit dispatch rule or token-based room configuration? 2. Is the MicroSIP participant showing as a
SIP
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 docs
b
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 import MultilingualModel 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): # Insert a row into call_sessions and return session_id 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 ) @breezy-insurance-66772.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() # Create call_sessions row and set ctx.session_id # NOTE: determine customer_id and agent_id according to your app logic. # For now, we attempt to infer caller from ctx.room name; adapt as needed. inferred_caller = None try: # ctx.room is a RoomInfo-like object; fallback to string room_name = ctx.room.name if hasattr(ctx.room, "name") else str(ctx.room) except Exception: room_name = str(ctx.room) customer_id = None # set if you can derive customer_id from caller or auth agent_id = None # set if you have agent mappings in DB async with pool.acquire() as conn: try: ctx.session_id = await create_call_session(conn, room_name, caller=inferred_caller, 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) # insert into DB 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: # Update call_sessions row with end time and duration end_time = datetime.utcnow() duration = int((end_time - start_time).total_seconds()) try: async with pool.acquire() as conn: if ctx.session_id: 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) this is the error : (venv) PS D:\AgnoX> python app/agents/openai_agent.py dev Traceback (most recent call last): File "D:\AgnoX\app\agents\openai_agent.py", line 11, in <module> from livekit.plugins.turn_detector import MultilingualModel ImportError: cannot import name 'MultilingualModel' from 'livekit.plugins.turn_detector'
t
You're hitting the ImportError because
MultilingualModel
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:
Copy code
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.:
Copy code
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&#39;s turn detection with transformers | Turn detection and interruptions | LiveKit Docs
b
give me the full code with fixed
t
Below is your script with the corrected import and a few small fixes so it runs as intended. I preserved your logic and added the corrected import for
MultilingualModel
. Keep your environment, dependencies, and model files installed as discussed earlier.
Copy code
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).
b
give me the testing step
t
Responding to your request for testing steps for the fixed agent script and verifying MicroSIP audio/TTS. 1) Prechecks — environment & dependencies • Confirm env vars:
DATABASE_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.
b
(venv) PS D:\AgnoX> python app/agents/openai_agent.py dev DEBUGasyncioUsing proactor: IocpProactor 104208.758 DEBUG asyncio Using proactor: IocpProactor DEVlivekit.agentsWatching D:\AgnoX\app\agents 104208.763 DEV livekit.agents Watching D:\AgnoX\app\agents DEBUGasyncioUsing proactor: IocpProactor 104210.885 DEBUG asyncio Using proactor: IocpProactor ERRORlivekit.agentsworker failed Traceback (most recent call last): File "D:\AgnoX\venv\lib\site-packages\livekit\agents\cli\cli.py", line 1288, in _worker_run await server.run(devmode=args.devmode, unregistered=jupyter) File "D:\AgnoX\venv\lib\site-packages\livekit\agents\worker.py", line 607, in run raise ValueError("ws_url is required, or add LIVEKIT_URL in your environment") ValueError: ws_url is required, or add LIVEKIT_URL in your environment 104210.896 ERROR livekit.agents worker failed Traceback (most recent call last): File "D:\AgnoX\venv\lib\site-packages\livekit\agents\cli\cli.py", line 1288, in _worker_run await server.run(devmode=args.devmode, unregistered=jupyter) File "D:\AgnoX\venv\lib\site-packages\livekit\agents\worker.py", line 607, in run raise ValueError("ws_url is required, or add LIVEKIT_URL in your environment") ValueError: ws_url is required, or add LIVEKIT_URL in your environment Process SpawnProcess-1: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\multiprocessing\process.py", line 314, in _bootstrap self.run() File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\multiprocessing\process.py", line 108, in run self._target(*self._args, **self._kwargs) File "D:\AgnoX\venv\lib\site-packages\livekit\agents\cli\cli.py", line 1311, in _run_worker loop.run_until_complete(server.aclose()) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 649, in run_until_complete return future.result() File "D:\AgnoX\venv\lib\site-packages\livekit\agents\worker.py", line 858, in aclose raise RuntimeError("cannot simulate job, the worker is closed") RuntimeError: cannot simulate job, the worker is closed (venv) PS D:\AgnoX> ^C (venv) PS D:\AgnoX>
t
You're seeing the worker fail because LiveKit connection info isn't set. To fix that and re-run the agent, do the following. 1) Set LiveKit server URL (WebSocket) in env • Add LIVEKIT_URL to your .env.local (or export in shell) with the LiveKit server address, e.g.: ◦ LIVEKIT_URL=wss://your-livekit.example.com • If using self-hosted LiveKit behind a load balancer use the wss:// endpoint reachable from your agent process. 2) Also ensure these env vars are present • LIVEKIT_API_KEY and LIVEKIT_API_SECRET (if your setup requires them) • OPENAI_API_KEY • DATABASE_URL 3) Reload env and re-run • Restart your shell/IDE or ensure dotenv loads .env.local • Run the agent again: ◦ python app/agents/openai_agent.py dev 4) Verify startup logs • Successful run should show no ValueError and show agent initialization messages instead of "ws_url is required". • If you see authentication errors, confirm API key/secret are correct and that LIVEKIT_URL is reachable from your machine (no firewall/NAT blocking). If it still fails, paste: • The exact LIVEKIT_URL value you set (mask secrets), or tell me whether you're using LiveKit Cloud or self-hosted • Any new traceback lines after rerunning — I’ll point to the next fix.