brief-evening-79958
12/02/2025, 11:50 AMtall-airline-16756
12/02/2025, 11:50 AMtall-airline-16756
12/02/2025, 11:51 AMuv run agent.py dev).
• Place a test inbound call and watch the LiveKit logs for the room creation and agent join events — if the SIP caller hears only dial tone it usually means no agent has published audio yet.
If you can, please provide:
• The agent name you configured (exact string), and the dispatch rule JSON (or paste the agents section).
• Whether the agent process shows any errors or logs when the inbound call arrives.
• Whether the SIP participant appears in the LiveKit room (participant kind: SIP) and any error codes in logs.
What I can help with next
• Validate your dispatch rule JSON and agent name for mismatches.
• Walk through agent startup and session.generate_reply() usage so the agent publishes audio immediately.
• Help interpret specific logs or error messages you paste here.
Send the dispatch rule and a short snippet of your agent logs when the call arrives and I’ll check them for the most likely cause.
Sources: Agents telephony integration | LiveKit docs | Accepting inbound calls | LiveKit docs | SIP troubleshooting guide | LiveKit docsbrief-evening-79958
12/02/2025, 11:53 AMRoomIO -> RecorderIO -> AgentSession ->
RecorderIO -> TranscriptSynchronizer -> RoomIO
171624.782 DEBUG livekit.agents using audio io: RoomIO -> RecorderIO -> AgentSession ->
RecorderIO -> TranscriptSynchronizer -> RoomIO
2025-12-02 171624,785 - livekit.agents - DEBUG - using transcript io: AgentSession -> TranscriptSynchronizer -> RoomIO
171624.785 DEBUG livekit.agents using transcript io: AgentSession -> TranscriptSynchronizer ->
RoomIO
2025-12-02 171624,787 - __mp_main__ - INFO - Agent session started and conversation completed
171624.787 INFO __mp_main__ Agent session started and conversation completed
2025-12-02 171624,790 - app.services.customer_service - INFO - ✅ Session ended: ID=203, Duration=0s, Handled by
=ai
171624.790 INFO app.services.cu… ✅ Session ended: ID=203, Duration=0s, Handled by=ai
2025-12-02 171624,797 - app.services.queue_manager - INFO - Marked queue entry 198 as completed
171624.797 INFO app.services.qu… Marked queue entry 198 as completed
2025-12-02 171624,799 - __mp_main__ - INFO - Session 203 completed (resolved by AI)
171624.799 INFO __mp_main__ Session 203 completed (resolved by AI)
2025-12-02 171633,964 - livekit.plugins.openai - DEBUG - OpenAI Realtime API response done but not complete with status: cancelled
171633.964 DEBUG livekit.plugins… OpenAI Realtime API response done {"event_id":
but not complete with status: "resp_CiJ7v8oLTjB12U097E30O",
cancelled "event_response_status":
"cancelled"}
2025-12-02 171646,577 - livekit.agents - INFO - closing agent session due to participant disconnect (disable via RoomInputOptions.close_on_disconnect=False)
171646.577 INFO livekit.agents closing agent session due to {"participant": "sip_+15183171307",
participant disconnect (disable via "reason": "CLIENT_INITIATED"}
RoomInputOptions.close_on_disconne
ct=False)
2025-12-02 171646,581 - livekit.agents - DEBUG - stream closed
171646.581 DEBUG livekit.agents stream closed {"participant": "sip_+15183171307", "source":
"SOURCE_MICROPHONE"}
2025-12-02 171646,585 - livekit.agents - DEBUG - input stream detached
171646.585 DEBUG livekit.agents input stream detached {"participant": "sip_+15183171307", "source":
"SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"]}
2025-12-02 171646,590 - livekit.agents - DEBUG - session closed
171646.590 DEBUG livekit.agents session closed {"reason": "participant_disconnected", "error": null}tall-airline-16756
12/02/2025, 11:53 AMsip_+15183171307 and audio input starts, then immediately detaches.
• Agent session shows "Agent session started and conversation completed" with Duration=0s, then OpenAI realtime response shows status "cancelled" and the session closes with reason participant_disconnected.
Immediate items to verify or change
1. Confirm the agent publishes audio (calls session.generate_reply() or otherwise publishes TTS) for inbound calls. If the agent never publishes audio the SIP caller will hear only dial tone and the session may end quickly.
◦ If you do not currently call session.generate_reply() on session start, add a short greeting so the agent speaks first.
1. Check RoomInputOptions.close_on_disconnect behavior. Your logs show session closed due to participant disconnect. If the SIP client briefly registers then disconnects, the agent will close. Set RoomOptions / RoomInputOptions.close_on_disconnect=False if you want the agent to remain when the SIP participant disconnects briefly.
2. Inspect why OpenAI Realtime was "cancelled". That can happen if the realtime response was interrupted (network or client disconnect). Look for network errors or timeouts between 171624 and 171633 in your agent logs or the platform logs.
3. Verify SIP client (MicroSIP) behavior:
◦ Ensure MicroSIP stays connected after call setup and is not terminating the call immediately (check MicroSIP logs/call timer).
◦ Confirm audio codecs and RTP settings match your SIP trunk / LiveKit Phone Number.
If you want, share these things and I’ll check them:
• The part of your agent code that handles inbound sessions (show the handler around session start and whether you call session.generate_reply()), and
• Your dispatch rule JSON (the agents section) and whether you set close_on_disconnect or RoomOptions.
Which of the above would you like me to look at first?brief-evening-79958
12/02/2025, 11:58 AMRoomIO -> RecorderIO -> AgentSession ->
RecorderIO -> TranscriptSynchronizer -> RoomIO
171755.718 DEBUG livekit.agents using audio io: RoomIO -> RecorderIO -> AgentSession ->
RecorderIO -> TranscriptSynchronizer -> RoomIO
2025-12-02 171755,721 - livekit.agents - DEBUG - using transcript io: AgentSession -> TranscriptSynchronizer -> RoomIO
171755.721 DEBUG livekit.agents using transcript io: AgentSession -> TranscriptSynchronizer ->
RoomIO
2025-12-02 171755,724 - __mp_main__ - INFO - Agent session started and conversation completed
171755.724 INFO __mp_main__ Agent session started and conversation completed
2025-12-02 171755,727 - app.services.customer_service - INFO - ✅ Session ended: ID=204, Duration=0s, Handled by
=ai
171755.727 INFO app.services.cu… ✅ Session ended: ID=204, Duration=0s, Handled by=ai
2025-12-02 171755,733 - app.services.queue_manager - INFO - Marked queue entry 199 as completed
171755.733 INFO app.services.qu… Marked queue entry 199 as completed
2025-12-02 171755,736 - __mp_main__ - INFO - Session 204 completed (resolved by AI)
171755.736 INFO __mp_main__ Session 204 completed (resolved by AI)
2025-12-02 171857,090 - livekit.agents - DEBUG - executing tool
171857.090 DEBUG livekit.agents executing tool {"function": "transfer_to_human", "arguments":
"{\"reason\":\"Customer requested to speak with a human
agent.\"}", "speech_id": "speech_d5cbeb49afba"}
2025-12-02 171857,094 - __mp_main__ - INFO - Transfer requested: Customer requested to speak with a human agent.
171857.094 INFO __mp_main__ Transfer requested: Customer requested to speak with a human agent.
2025-12-02 171857,096 - livekit.agents - DEBUG - tools execution completed
171857.096 DEBUG livekit.agents tools execution completed {"speech_id": "speech_d5cbeb49afba"}
2025-12-02 171918,160 - livekit.agents - INFO - closing agent session due to participant disconnect (disable via RoomInputOptions.close_on_disconnect=False)
171918.160 INFO livekit.agents closing agent session due to {"participant": "sip_+918778869983", participant disconnect (disable via "reason": "CLIENT_INITIATED"}
RoomInputOptions.close_on_disconne
ct=False)
2025-12-02 171918,165 - livekit.agents - DEBUG - stream closed
171918.165 DEBUG livekit.agents stream closed {"participant": "sip_+918778869983", "source":
"SOURCE_MICROPHONE"}
2025-12-02 171918,170 - livekit.agents - DEBUG - input stream detached
171918.170 DEBUG livekit.agents input stream detached {"participant": "sip_+918778869983", "source":
"SOURCE_UNKNOWN", "accepted_sources":
["SOURCE_MICROPHONE"]}
2025-12-02 171918,177 - livekit.agents - DEBUG - session closed
171918.177 DEBUG livekit.agents session closed {"reason": "participant_disconnected", "error": null}
also i attached the agent codetall-airline-16756
12/02/2025, 11:58 AMsession.generate_reply() or publish TTS/audio.
2. Your SIP dispatch rule JSON (the agents section) and any RoomOptions or close_on_disconnect settings you pass.
Quick checks you can try now
• If you don’t already, add a short session.generate_reply("Hello, this is agent...") immediately on session start so the agent speaks first.
• Set RoomOptions (or RoomInputOptions.close_on_disconnect=False) to avoid immediate session close on brief SIP disconnects.
Send the two snippets and I’ll review them and point out the exact changes.brief-evening-79958
12/02/2025, 11:59 AMtall-airline-16756
12/02/2025, 12:00 PMsession.generate_reply() (or other TTS/publish) immediately after session starts so the agent speaks first.
• Any RoomOptions / RoomInputOptions you set (especially close_on_disconnect).
• How you handle OpenAI Realtime responses and cancellation errors.
Also confirm:
• MicroSIP call stays active (no immediate hangup) and codecs match your SIP trunk.
Send the code snippet and a quick note whether MicroSIP shows the call as ended immediately; I’ll point out exact lines to change.brief-evening-79958
12/02/2025, 12:11 PMtall-airline-16756
12/02/2025, 12:11 PMclose_on_disconnect set to False so the agent stays if the SIP participant disconnects briefly.
Paste the code and confirm the three items and I’ll return a complete, corrected agent file ready to run.brief-evening-79958
12/02/2025, 12:12 PMtall-airline-16756
12/02/2025, 12:12 PMclose_on_disconnect=False, but I need to see your current agent file to adapt imports, helper functions, and any app-specific utilities so the replacement integrates cleanly.
Please paste the agent file you want replaced (the entire file or at least the first ~200 lines). If you prefer a generic example instead of adapting your exact file, confirm and I’ll provide a ready-to-run example that includes:
• agent registration named "AgnoX-AI-Agent"
• speaking the greeting "Hello, this is AgnoX. How can I help you today?"
• RoomOptions with close_on_disconnect=False
• basic OpenAI realtime handling and safe cancellation handling
Which do you want: paste your file for an adapted fix, or receive a standalone generic example?brief-evening-79958
12/03/2025, 4:31 AMtall-airline-16756
12/03/2025, 4:31 AMAgentSession with separate STT and TTS providers (example: assemblyai/universal-streaming for STT and cartesia/sonic-3 or openai/tts-1 for TTS). I’ll provide a ready-to-run agent file using RoomOptions with close_on_disconnect=False and a first-turn session.generate_reply() greeting.
Which option do you want?
Sources: Agent session | LiveKit docs | Voice AI quickstart | LiveKit docsbrief-evening-79958
12/03/2025, 4:40 AMtall-airline-16756
12/03/2025, 4:40 AMRoomOptions with close_on_disconnect=False
• Starts the session and immediately calls session.generate_reply("Hello, this is AgnoX. How can I help you today?") so the caller hears the greeting
• Handles OpenAI realtime cancellation safely and logs useful errors
Before I return the file, confirm:
• You want the OpenAI Realtime example (yes/no).
• Any preferred voice for TTS (if none, I’ll use a generic OpenAI TTS voice).brief-evening-79958
12/03/2025, 4:42 AMtall-airline-16756
12/03/2025, 4:42 AM@server.rtc_session) and is ready to adapt into your project — ensure your environment variables (LIVEKIT_*, OPENAI_API_KEY) are set.
Save as, for example, app/agents/realtime_agent.py and run with your usual dev command.
import os
import asyncio
from dotenv import load_dotenv
from livekit import agents, rtc
from livekit.agents import AgentServer, AgentSession, JobContext, Agent
from livekit.plugins import openai, noise_cancellation, silero
from livekit.plugins.turn_detector import MultilingualModel
load_dotenv(".env.local")
AGENT_NAME = "AgnoX-AI-Agent"
GREETING = "Hello, this is AgnoX. How can I help you today?"
server = AgentServer()
class AgnoXAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a friendly customer service voice assistant. Respond concisely and helpfully."
)
@server.rtc_session(agent_name=AGENT_NAME)
async def realtime_agent(ctx: JobContext):
# Build the OpenAI Realtime model (handles STT + TTS)
realtime_model = openai.realtime.RealtimeModel(
voice="alloy", # or choose another available voice
temperature=0.5,
modalities=["audio"], # ensure audio I/O
)
# Create AgentSession with VAD and turn detection
session = AgentSession(
llm=realtime_model,
vad=silero.VAD.load(),
turn_detection=MultilingualModel(),
)
# Use RoomOptions to avoid closing the session on brief SIP disconnects
room_options = rtc.RoomOptions(
close_on_disconnect=False
)
# Provide noise cancellation optimized for telephony when participant is SIP
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()
# Start the session bound to the room
await session.start(
room=ctx.room,
agent=AgnoXAgent(),
room_options=room_options,
room_input_options=rtc.RoomInputOptions(noise_cancellation=telephony_noise),
)
try:
# Wait briefly to ensure media paths are established before speaking
await asyncio.sleep(1.0)
# Speak the initial greeting so MicroSIP caller hears the agent immediately
await session.generate_reply(
instructions=f"Say: '{GREETING}' in a warm, natural tone."
)
# Keep the session alive to handle conversation.
# AgentSession will handle the ongoing loop; await session.wait_closed() to
# return when the session ends.
await session.wait_closed()
except Exception as e:
# Log error and ensure session closed
print("Agent error:", e)
try:
await session.close()
except Exception:
pass
if __name__ == "__main__":
agents.cli.run_app(server)
Notes and quick checks after deploying this file:
• Ensure your dispatch rule lists "AgnoX-AI-Agent" (your existing dispatch rule already does).
• Confirm .env.local contains LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET, and OPENAI_API_KEY.
• Start the agent and then place a MicroSIP call; watch agent logs for the "Agent session started" and the TTS/greeting events.
• If the caller still experiences silence, check MicroSIP call duration (ensure it stays connected at least ~3–5s) and that RTP codecs match the SIP trunk.
If you want, I can adapt this to match any utility functions or imports in your repo if you paste your current agent file.
Sources: Agents telephony integration | LiveKit docs | OpenAI and LiveKit | LiveKit docs | Voice AI quickstart | LiveKit docs | sip | livekit/livekit_composite | DeepWiki | OpenAI Realtime API plugin guide | LiveKit docsbrief-evening-79958
12/03/2025, 4:43 AMtall-airline-16756
12/03/2025, 4:43 AMclose_on_disconnect=False, and emits live transcription events (prints caller transcripts and agent replies). Save as app/agents/realtime_agent_with_transcript.py and run the same way as before.
import os
import asyncio
from dotenv import load_dotenv
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")
AGENT_NAME = "AgnoX-AI-Agent"
GREETING = "Hello, this is AgnoX. How can I help you today?"
server = AgentServer()
class AgnoXAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a friendly customer service voice assistant. Respond concisely and helpfully."
)
@server.rtc_session(agent_name=AGENT_NAME)
async def realtime_agent(ctx: JobContext):
realtime_model = openai.realtime.RealtimeModel(
voice="alloy",
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()
# Handlers for live transcription and LLM responses
async def on_transcript(participant, transcript_text, is_final):
# Called when speech is transcribed from the caller
tag = "FINAL" if is_final else "PARTIAL"
print(f"[TRANSCRIPT][{tag}] participant={participant}: {transcript_text}")
async def on_agent_speech(speech_text, speech_id=None):
# Called when the agent has produced a reply (text from LLM)
print(f"[AGENT_REPLY] {speech_text} (speech_id={speech_id})")
# Start session and attach handlers
await session.start(
room=ctx.room,
agent=AgnoXAgent(),
room_options=room_options,
room_input_options=rtc.RoomInputOptions(noise_cancellation=telephony_noise),
)
# Register transcript callback with the session's transcript pipeline
# (AgentSession exposes transcript events; attach as available in SDK)
try:
# Some SDKs expose a simple callback registration; adjust if your version differs
session.on("transcript", on_transcript)
session.on("agent_speech", on_agent_speech)
except Exception:
# If callback API differs, fallback to polling or rely on AgentSession logs
pass
try:
# Ensure media is stable before speaking
await asyncio.sleep(1.0)
# Speak the greeting (TTS via Realtime)
await session.generate_reply(
instructions=f"Say: '{GREETING}' in a warm, natural tone."
)
# Main loop: keep session alive and rely on event callbacks for transcripts
await session.wait_closed()
except Exception as e:
print("Agent error:", e)
try:
await session.close()
except Exception:
pass
if __name__ == "__main__":
agents.cli.run_app(server)
Quick notes
• This example registers simple callbacks on_transcript and on_agent_speech and prints partial/final transcripts and agent replies. If your SDK version exposes different event names or a different registration method, paste the agent code and I’ll adapt the handler registration for your version.
• Ensure .env.local has LIVEKIT and OPENAI keys and LIVEKIT_URL.
• Test flow: start agent, place MicroSIP call, watch logs for [TRANSCRIPT] entries and the agent greeting.
• If you want transcripts sent to an external store (DB or websocket) instead of printing, tell me where and I’ll add that.
Would you like me to adapt the callback registration to match your current agent file (paste it) or include saving transcripts to a file/DB?brief-evening-79958
12/03/2025, 4:45 AMtall-airline-16756
12/03/2025, 4:45 AMclose_on_disconnect=False.
I’ll produce that file now. Do you want transcripts:
• printed to logs (current example), or
• also saved to a file (e.g., CSV/text)?
Reply with "logs" or "file" and I’ll send the final agent file accordingly.brief-evening-79958
12/03/2025, 4:47 AMtall-airline-16756
12/03/2025, 4:47 AMbrief-evening-79958
12/03/2025, 4:48 AMtall-airline-16756
12/03/2025, 4:48 AMtranscripts table.
One quick detail before I produce the file: which environment variable holds your Postgres connection URL (e.g., DATABASE_URL or POSTGRES_URL)? If you don’t want to share the actual URL, just give the env var name you’ll use and I’ll reference it in the code.brief-evening-79958
12/03/2025, 4:49 AMtall-airline-16756
12/03/2025, 4:49 AMtranscripts table using the DATABASE_URL env var. Save as e.g. app/agents/realtime_agent_db.py and run as you did before.
Key behaviors implemented:
• Agent name: "AgnoX-AI-Agent" (matches your dispatch rule)
• Initial spoken greeting: "Hello, this is AgnoX. How can I help you today?"
• Uses OpenAI Realtime model for STT/TTS (speech I/O)
• RoomOptions close_on_disconnect=False
• Prints transcripts to logs and inserts each transcript row into Postgres (partial and final)
• Async DB connection pooling via asyncpg
• Safe handling of OpenAI realtime cancellation and session lifecycle
Code (save and run):
import os
import asyncio
import logging
from dotenv import load_dotenv
import asyncpg
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") # must be set in .env.local
OPENAI_VOICE = "alloy" # change if desired
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 insert_transcript(pool, session_id, speaker, text, confidence=1.0, sentiment=None):
# Inserts a transcript row; session_id may be None if unknown
async with pool.acquire() as conn:
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):
# Create DB pool and attach to ctx so multiple sessions can reuse
# (If you start many worker processes, consider creating pool at process start)
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"],
)
# Create AgentSession with VAD and turn detection
session = AgentSession(
llm=realtime_model,
vad=silero.VAD.load(),
turn_detection=MultilingualModel(),
)
# RoomOptions to avoid closing on brief SIP disconnects
room_options = rtc.RoomOptions(close_on_disconnect=False)
# Telephony-optimized noise cancellation callback
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()
# Handlers for transcripts - adapt if SDK event names differ
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(f"[TRANSCRIPT][{tag}] speaker={speaker}: {transcript_text}")
# Try insert into DB (session_id from ctx if available)
session_id = getattr(ctx, "session_id", None)
try:
await insert_transcript(pool, 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(f"[AGENT_REPLY] {speech_text} (speech_id={speech_id})")
# Save agent reply as well (speaker = agent)
session_id = getattr(ctx, "session_id", None)
try:
await insert_transcript(pool, 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 for transcripts and agent speech
# Note: method names for registering events may vary by SDK version.
# Try commonly exposed APIs; fallback to polling if necessary.
try:
session.on("transcript", handle_transcript)
except Exception:
# If `on` isn't available, SDK may expose `transcript_callback` property or different API.
LOG.debug("session.on('transcript') not available; transcripts may still appear in logs")
try:
session.on("agent_speech", handle_agent_reply)
except Exception:
LOG.debug("session.on('agent_speech') not available; agent replies may still appear in logs")
# Optional: If you have a call_sessions table and want to set session_id in transcripts,
# create a call_session entry here and attach ctx.session_id accordingly.
# Example placeholder (uncomment/adapt if you maintain session records):
# async with pool.acquire() as conn:
# row = await conn.fetchrow("INSERT INTO call_sessions(...) VALUES(...) RETURNING session_id")
# ctx.session_id = row["session_id"]
try:
# Give media a moment to be ready
await asyncio.sleep(1.0)
# Speak initial greeting so caller hears agent immediately
await session.generate_reply(
instructions=f"Say: '{GREETING}' in a warm, natural tone."
)
# Wait until session is closed by participant or system
await session.wait_closed()
LOG.info("Agent session ended normally")
except Exception as e:
LOG.exception("Agent session error: %s", e)
finally:
# Ensure session closed and pool is released (pool can remain for reuse if you prefer)
try:
await session.close()
except Exception:
pass
try:
await pool.close()
except Exception:
pass
if __name__ == "__main__":
agents.cli.run_app(server)
Quick deployment notes
• Add DATABASE_URL to .env.local, e.g.:
DATABASE_URL=postgresql://user:password@host:5432/dbname
• Ensure your transcripts table exists with the schema you provided.
• If you record call sessions in call_sessions and want to link transcripts, create the call session row before inserting transcripts and set ctx.session_id accordingly — I left a commented example where you can insert and attach ctx.session_id.
• If your SDK version uses different event registration APIs (e.g., session.on_transcript = ...), paste your current agent file and I’ll adapt the registration lines.
If you want, I can:
• Adapt the file to create and set call_sessions.session_id automatically.
• Change transcript storage to batch inserts or include sentiment analysis before save.
Which of those would you prefer next?brief-evening-79958
12/03/2025, 4:53 AMcall_sessions.session_id automatically.
also refer this file toootall-airline-16756
12/03/2025, 4:53 AMcall_sessions row at session start, sets ctx.session_id to that ID, and uses it for transcript inserts.
• Uses OpenAI Realtime for STT/TTS, speaks the greeting, logs transcripts to console, and saves partial/final transcripts to your Postgres transcripts table.
• Uses RoomOptions(close_on_disconnect=False) and telephony noise cancellation.
• Uses DATABASE_URL from .env and asyncpg connection pool.
I need one small confirmation before I generate the file:
• Provide your call_sessions table schema (columns and types). If you don’t provide it, I will create a minimal insert that assumes a table with at least: session_id SERIAL PRIMARY KEY, room VARCHAR, caller VARCHAR, and started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP. Confirm OK or paste your exact schema.brief-evening-79958
12/03/2025, 4:54 AMtall-airline-16756
12/03/2025, 4:54 AMcall_sessions row at session start and sets ctx.session_id.
• Uses OpenAI Realtime for STT/TTS, speaks the greeting, and logs live partial/final transcripts.
• Inserts transcripts into your Postgres transcripts table linked by session_id.
• Uses RoomOptions(close_on_disconnect=False) and telephony noise cancellation.
• Uses asyncpg connection pool via DATABASE_URL from your .env.
Save as app/agents/realtime_agent_with_db_session.py and run as before.
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
)
@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()
# 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)
Notes and minor integration tips
• Customer/agent mapping: I left customer_id and agent_id as None. If you can extract a customer from the incoming SIP caller or a lookup, set those values before creating the call_sessions row.
• If you want to record call_metadata (SIP headers, caller number, trunk ID), pass a dict to create_call_session(..., call_metadata={...}).
• If your SDK exposes different event registration APIs (e.g., session.on_transcript = ...), paste your SDK version or current agent file and I’ll adapt registration lines.
• Ensure .env.local contains LIVEKIT and OPENAI keys and DATABASE_URL.
• Test flow: start agent, place MicroSIP call, watch logs for created session id, greeting TTS, transcripts printed and saved in DB.
If you want, I can:
• Fill customer_id automatically by parsing the SIP caller ID.
• Add sentiment analysis of transcripts before save (store in sentiment column).
• Batch transcript inserts for performance.
Which enhancement would you like next?brief-evening-79958
12/03/2025, 4:55 AMsentiment column).
and give testing guidetall-airline-16756
12/03/2025, 4:55 AMbrief-evening-79958
12/03/2025, 5:01 AMbrief-evening-79958
12/03/2025, 5:03 AM