cuddly-vr-85751
11/21/2025, 2:14 PMtall-airline-16756
11/21/2025, 2:14 PMtall-airline-16756
11/21/2025, 2:15 PMcuddly-vr-85751
11/21/2025, 2:15 PMtall-airline-16756
11/21/2025, 2:16 PMdocker pull livekit/generate
docker run --rm -it -v $PWD:/output livekit/generate
• The generator will prompt for values (domain, API key/secret, etc.) and produce files in your current directory, including cloud_init.*.yaml, init_script.sh, Caddy and Docker Compose configs.
2) Copy files to the Ubuntu VM
• If you generated locally, copy the generated files to the VM (replace USER and VM_IP):
scp -r /path/to/generated/files USER@VM_IP:~/livekit-deploy
ssh USER@VM_IP
cd ~/livekit-deploy
• Or generate directly on the VM by running the generator there.
3) Run the init script to install Docker, Docker Compose, and configure the service
• Make the init script executable and run it with sudo:
sudo chmod +x init_script.sh
sudo ./init_script.sh
• The script installs Docker and Docker Compose, places the Docker Compose files, configures Caddy for TLS, and registers a systemd service (commonly named livekit-docker).
4) Start and enable the LiveKit service
• Start the service and enable it to run on boot:
sudo systemctl start livekit-docker
sudo systemctl enable livekit-docker
• To stop or check status:
sudo systemctl stop livekit-docker
sudo systemctl status livekit-docker
5) Verify containers are running
• Confirm Docker Compose started the LiveKit containers:
sudo docker ps
You should see containers for livekit-server, caddy, and other components.
6) Confirm DNS, TLS, and ports
• Ensure your domain resolves to the VM’s IP:
dig +short your.domain.tld
• Check that Caddy obtained TLS certificates and is serving HTTPS on port 443.
• Verify UDP ports (3478 and 50000–60000) are reachable from clients (STUN/TURN and media UDP ports).
7) Firewall setup (ufw example)
• Allow required ports with ufw:
sudo ufw allow 22/tcp # SSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 7881/tcp
sudo ufw allow 3478/udp
sudo ufw allow 50000:60000/udp
sudo ufw enable
sudo ufw status
8) Test a client connection
• Use your app (configured with the API key and domain you provided to the generator) to connect to the LiveKit server and confirm audio/video sessions work.
9) Logs and troubleshooting
• View LiveKit logs:
sudo journalctl -u livekit-docker -f
• Or inspect container logs:
sudo docker-compose -f /path/to/docker-compose.yml logs -f
If you want, I can:
• Provide the exact commands for generating config interactively (sample answers for prompts).
• Show a sample docker run input or a minimal docker-compose.yml.
• Walk through verifying UDP port reachability from a remote client.
Which follow-up would you like?cuddly-vr-85751
11/21/2025, 3:33 PMtall-airline-16756
11/21/2025, 3:33 PMcuddly-vr-85751
11/21/2025, 3:34 PMtall-airline-16756
11/21/2025, 3:34 PM@function_tool that returns free slots,
• wiring so the LLM can call that function,
• an audio/text response after the function runs.
Do you want:
• exact code that uses deepgram STT + groq LLM + cartesia TTS (your current setup), or
• a minimal example that’s LLM-agnostic (easier to test)?
Tell me which and I’ll provide the full code snippet.
Sources: Deploy to a VM | LiveKit docs | Deploy to Kubernetes | LiveKit docs | Tool definition and use | LiveKit docs | Testing and evaluation | LiveKit Docs | Running LiveKit on AWScuddly-vr-85751
11/21/2025, 3:35 PMtall-airline-16756
11/21/2025, 3:35 PMget_free_slots which the LLM will call when the user says "get free slots". It also shows how to start the agent session in a LiveKit room. Adjust imports/credentials as needed from your environment.
Save as agent.py and run it on the same machine that connects to your LiveKit room (or adapt entrypoint as you already do).
from dotenv import load_dotenv
load_dotenv()
import asyncio
from typing import List
from livekit.agents import Agent, JobContext, WorkerOptions, cli, function_tool
from livekit.agents.voice import AgentSession
from livekit.agents.context import RunContext
from livekit.plugins import silero, deepgram, groq, cartesia
# --- Agent with tool ---
class SupportAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a helpful support agent. Start by saying your name is Tom and begin the conversation.",
stt=deepgram.STT(), # speech -> text
llm=groq.LLM(model="llama-3.1-8b-instant"), # language model
tts=cartesia.TTS(model="sonic-3", voice="e3087ad8-7018-4154-9a87-11577f916cd4"), # text -> speech
vad=silero.VAD.load(), # voice activity detection
)
@function_tool()
async def get_free_slots(self, ctx: RunContext, date: str = None) -> List[str]:
"""
Return available free slots for a given date.
The LLM will call this function when user intent matches 'get free slots'.
Args:
date: Optional date string (YYYY-MM-DD). If None, return generic slots.
Returns:
List[str]: available time slots as strings.
"""
# Replace with real calendar/API lookup as needed.
await asyncio.sleep(0.5) # simulate I/O
if date:
return [f"{date} 09:00", f"{date} 11:00", f"{date} 14:00"]
return ["10:00 AM", "2:00 PM", "4:30 PM"]
# Optional: override on_message or similar hook if you need more control
# (Many agent frameworks automatically route LLM function calls for you.)
# --- Entrypoint used by worker/cli ---
async def entrypoint(ctx: JobContext):
"""
JobContext provides room and other runtime info.
This starts an AgentSession using SupportAgent and connects to the LiveKit room
provided in ctx.room.
"""
agent = SupportAgent()
# Optional: an initial spoken greeting via TTS
# agent.say will be converted to audio using the configured TTS
await agent.say("Hi, my name is Tom. How can I help you today?")
# Start session: connects agent to the room in ctx
await AgentSession().start(agent=agent, room=ctx.room)
def run():
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="support", port=8081))
if __name__ == "__main__":
run()
How this triggers the function when the user says "get free slots":
• STT (Deepgram) transcribes user speech to text.
• The LLM sees the transcript and the available function get_free_slots (its name and docstring).
• When the transcript matches the user's intent (e.g., "get free slots for tomorrow"), the LLM will call get_free_slots with parsed arguments (date etc.).
• The return value (list of slots) is available to the agent; the agent's LLM can then generate a verbal response which will be rendered via Cartesia TTS.
Notes & tips:
• Make the function signature and docstring clear so the LLM reliably maps user requests to the function.
• If you need exact phrase matching rather than LLM routing, you can intercept transcripts before LLM inference and call the function directly:
◦ Use an on_transcript or hook (or check inside your conversational handler) to run:
▪︎ if "get free slots" in transcript.lower(): await agent.get_free_slots(ctx, date=...)
• For production, replace the simulated slots with calls to your calendar or database.
• Keep credentials (Deepgram, Groq, Cartesia) in your environment (.env) as you already load with load_dotenv().
If you want, I can:
• Provide an example that parses phrases like "for tomorrow" into a date argument.
• Show how to intercept transcripts and call the function directly (exact match) before LLM runs.
Which follow-up would you like?cuddly-vr-85751
11/21/2025, 3:43 PMtall-airline-16756
11/21/2025, 3:43 PM@function_tool() inside your Agent class (e.g., get_free_slots). That registers the function so the LLM knows it exists and can call it.
2) How the LLM decides to call a function
• After STT produces a transcript, the transcript is passed into the LLM along with metadata about available functions (name, signature, docstring).
• The LLM uses intent understanding to decide whether the user’s request should invoke a registered function instead of returning a plain text reply. If intent matches (e.g., user asks “get free slots”), the LLM emits a function call with the chosen function name and parsed arguments.
3) Argument parsing & invocation
• The LLM returns structured arguments (based on the function signature) when it decides to call the function.
• The agent runtime maps those arguments to your Python method and invokes it (e.g., await agent.get_free_slots(ctx, date="2024-11-22")).
4) Function result handling
• Your function returns structured data (list/dict/primitive). The agent runtime captures that result and provides it back to the LLM as the function’s output.
• The LLM then continues the conversation using that output (for example, generating a spoken reply like “I found these slots: …”), which the agent sends via TTS.
5) Where you can intervene
• Pre-LLM interception: Inspect the STT transcript yourself and call the function directly for exact-match triggers (bypass LLM routing).
• Post-call handling: After the function returns, you can format or post-process the result before letting the LLM generate the final message or before directly using TTS to speak the result.
• Argument validation: Validate/normalize LLM-parsed args inside the function (e.g., parse “tomorrow” into a date).
6) Best practices
• Give functions clear names and docstrings so the LLM maps intent accurately.
• Use explicit typed arguments and simple return types (dict/list) to make parsing reliable.
• Keep side-effecting operations (DB writes, API calls) inside the function so the LLM only handles orchestration.
• If you need exact phrase behavior, do transcript-level checks and call functions directly.
If you want, I can:
• Show an example of the raw LLM function-call structure (input + function metadata + returned call).
• Provide code to intercept transcripts and call the function directly for exact matches.
Which would you like?cuddly-vr-85751
11/21/2025, 3:46 PMtall-airline-16756
11/21/2025, 3:47 PM@function_tool() (Python) or llm.tool() (Node).
• The LLM receives metadata (name, signature, docstring/schema). When user intent matches, the LLM emits a function call with parsed arguments.
• Runtime maps arguments to your function and invokes it (e.g., await agent.get_free_slots(ctx, date="...")).
• The function returns structured data (list/dict/primitive); runtime supplies that result back to the LLM so it can continue the conversation.
• Tools can raise errors to inform the LLM, or return None to be silent.
• Best practice: clear names, typed args, and precise docstrings for reliable mapping.
Tool advanced features
• Agent handoff: a tool can transfer control to another Agent (return an Agent instance or use llm.handoff()), creating multi-agent workflows.
• Interrupt control: block user interruptions during critical tool execution (use run options like disallow_interruptions()).
• RPC to frontend: tools can invoke JS-side RPC methods on participants (useful to access device data or prompt UI).
• Raw schema / JSON schema tools: define tools using JSON/Zod/TypedDict for strict parsing and compatibility with OpenAI-style function calling.
Tasks, Task Groups & short-lived workflows
• Tasks are focused, short-lived workflows that can take temporary control of a session and return results.
• Task groups chain tasks and maintain shared context; useful for multi-step flows (orders, triage, forms).
Pipeline customization & nodes
• Override pipeline nodes to change behavior:
◦ llm_node() — modify prompt, inject RAG, or change LLM call behavior.
◦ tts_node() — post-process TTS output (pronunciation fixes, audio transforms).
◦ on_enter() / on_user_turn_completed() — hooks for custom logic at key lifecycle points.
• Use these to inject external context, perform RAG lookups, or modify generation.
Dynamic context, RAG & external data
• Inject retrieved data into the conversation after user turns (e.g., fetch KB or DB results and add a system message).
• Use on_user_turn_completed to perform lookups then add context to the next LLM call.
Model Context Protocol (MCP) & external tool servers
• Load tool definitions from external MCP servers (Python-only support).
• Enables dynamic tool discovery and centralized tool hosting.
Testing & mocking
• mock_tools to simulate tool behavior in tests.
• Capture events like function_call, function_call_output, agent_handoff in integration tests.
• Use judge() to evaluate LLM output quality programmatically.
Runtime & session APIs
• Access `RunContext`/`JobContext` inside tools for session state, speech handles, and userdata.
• Update instructions and chat context at runtime (update_instructions, update_chat_ctx).
• Control session lifecycle with AgentSession().start(...) and session-level options.
Return values, errors & structured outputs
• Tools return structured types; runtime serializes results to the LLM.
• Raise ToolError (or equivalent) to send explicit error messages to the LLM.
• Prefer typed returns (TypedDict, list[str], etc.) for deterministic behavior.
Security & best practices
• Keep agents stateless; store session-specific data in userdata.
• Validate and sanitize arguments from the LLM inside the tool.
• Minimize side effects in functions when possible; wrap external calls with retries and errors.
Examples & common patterns
• Exact-match trigger: intercept STT transcript and call a function directly for phrase-level control.
• LLM-based routing: expose clear tools and rely on the LLM to call the appropriate tool.
• Handoff flow: intake agent uses tool to determine specialist → tool returns new Agent → session hands off.
• Frontend-dependent tool: tool calls participant RPC to fetch device location, then uses that data.
If you’d like, I can:
• Provide a concrete Python example showing: function tool + argument parsing + returning structured output + LLM response (full runnable snippet).
• Show how to implement agent handoff in Python.
• Show transcript interception to call tools on exact phrase matches.
• Show test code using mock_tools and assertions for function calls.
Which of these specific examples would you like next?
Sources: Tool definition and use | LiveKit docs | Agents and handoffs | LiveKit docs | Tasks and task groups | LiveKit docs | External data and RAG | LiveKit Docs | Agents v0.x migration guide - Python | LiveKit docscuddly-vr-85751
11/21/2025, 3:51 PMtall-airline-16756
11/21/2025, 3:51 PMfrom dotenv import load_dotenv
load_dotenv()
import asyncio
import time
import json
from datetime import datetime
from typing import List
from livekit.agents import Agent, JobContext, WorkerOptions, cli, function_tool
from livekit.agents.voice import AgentSession
from livekit.plugins import silero, deepgram, groq, cartesia
class SupportAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a helpful support agent. Start by saying your name is Tom and begin the conversation.",
stt=deepgram.STT(),
llm=groq.LLM(model="llama-3.1-8b-instant"),
tts=cartesia.TTS(model="sonic-3", voice="e3087ad8-7018-4154-9a87-11577f916cd4"),
vad=silero.VAD.load(),
)
@function_tool()
async def get_free_slots(self, date: str = None) -> List[str]:
return ["10:00 AM", "2:00 PM", "4:30 PM"]
async def entrypoint(ctx: JobContext):
agent = SupportAgent()
session = AgentSession()
# track start time
session_start = None
@session.on("starting")
def _on_starting():
nonlocal session_start
session_start = time.time()
# optional: log each conversation item as it arrives (real-time)
@session.on("conversation_item_added")
def _on_item(event):
# event.item has fields like role, text_content, timestamp
print(f"[LIVE] {event.item.role}: {event.item.text_content}")
# shutdown callback: save transcript + duration
async def _on_shutdown():
session_end = time.time()
duration_seconds = session_end - (session_start or session_end)
# session.history.to_dict() returns structured transcript messages
transcript = session.history.to_dict()
# Save to file (filename includes room name and timestamp)
fname = f"/tmp/transcript_{ctx.room.name}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
payload = {
"room": ctx.room.name,
"started_at": session_start,
"ended_at": session_end,
"duration_seconds": duration_seconds,
"transcript": transcript,
}
with open(fname, "w") as f:
json.dump(payload, f, indent=2)
print(f"Transcript saved to {fname}")
print(f"Total conversation duration: {duration_seconds:.2f} seconds")
# ensure shutdown callback runs when the JobContext shuts down
ctx.add_shutdown_callback(_on_shutdown)
# start the session (blocks until session ends)
await session.start(agent=agent, room=ctx.room)
def run():
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="support", port=8081))
if __name__ == "__main__":
run()
Notes:
• session.history.to_dict() gives structured messages with roles, text, and timestamps.
• ctx.add_shutdown_callback() ensures the shutdown logic runs when the session ends or the job is terminated.
• Use conversation_item_added for real‑time logging; starting marks the active start.
• Adjust the file path or replace the file save with a database/API call as needed.
Would you like an example that also:
• summarizes the transcript automatically, or
• computes per-speaker durations and counts? Sources: Observability data hooks | LiveKit docs | Agent session | LiveKit docs | Events and error handling | LiveKit docscuddly-vr-85751
11/21/2025, 4:06 PMtall-airline-16756
11/21/2025, 4:07 PMfrom dotenv import load_dotenv
load_dotenv()
import time
import json
import os
from datetime import datetime
from typing import List
from livekit.agents import Agent, JobContext, WorkerOptions, cli, function_tool
from livekit.agents.voice import AgentSession
from livekit.plugins import deepgram, groq, cartesia, silero
class SupportAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a helpful support agent. Start by saying your name is Tom.",
stt=deepgram.STT(),
llm=groq.LLM(model="llama-3.1-8b-instant"),
tts=cartesia.TTS(model="sonic-3", voice="e3087ad8-7018-4154-9a87-11577f916cd4"),
vad=silero.VAD.load(),
)
@function_tool()
async def get_free_slots(self, date: str = None) -> List[str]:
return ["10:00 AM", "2:00 PM", "4:30 PM"]
async def entrypoint(ctx: JobContext):
agent = SupportAgent()
session = AgentSession()
session_start = None
@session.on("starting")
def _on_starting():
nonlocal session_start
session_start = time.time()
async def _on_shutdown():
session_end = time.time()
duration_seconds = session_end - (session_start or session_end)
session_id = getattr(session, "id", None) or getattr(ctx.room, "sid", None) or ctx.room.name
transcript = session.history.to_dict() if hasattr(session, "history") else []
os.makedirs("transcripts", exist_ok=True)
fname = os.path.join(
"transcripts",
f"transcript_{session_id}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
)
payload = {
"session_id": session_id,
"started_at": session_start,
"ended_at": session_end,
"duration_seconds": duration_seconds,
"transcript": transcript,
}
with open(fname, "w") as f:
json.dump(payload, f, indent=2)
print(f"Saved: {fname}")
print(f"Session ID: {session_id}, Duration: {duration_seconds:.2f}s")
ctx.add_shutdown_callback(_on_shutdown)
await session.start(agent=agent, room=ctx.room)
def run():
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="support", port=8081))
if __name__ == "__main__":
run()
Notes:
• Session ID: attempts session.id, falls back to ctx.room.sid or ctx.room.name.
• Duration: simple wall-clock seconds between starting and shutdown.
• Transcript saved to ./transcripts/*.json using session.history.to_dict() when available.
Want this to also print per-speaker message counts or a short summary?cuddly-vr-85751
11/21/2025, 4:08 PMtall-airline-16756
11/21/2025, 4:08 PMctx.room.sid is async and returned a coroutine), so Python wrote something like <coroutine object Room.sid ...> into the filename which is invalid. Fix: await the async property or call a synchronous fallback and sanitize the session id before creating the filename.
Change only the session-id retrieval and filename creation. Replace your shutdown callback with this safe version:
async def _on_shutdown():
session_end = time.time()
duration_seconds = session_end - (session_start or session_end)
# get session id safely (await if coroutine, fallback to room.name)
session_id = None
try:
sid_attr = getattr(session, "id", None)
if callable(sid_attr):
sid_attr = sid_attr()
if asyncio.iscoroutine(sid_attr):
session_id = await sid_attr
else:
session_id = sid_attr
except Exception:
session_id = None
if not session_id:
# ctx.room.sid may be async; try awaiting if available
try:
room_sid = getattr(ctx.room, "sid", None)
if callable(room_sid):
room_sid = room_sid()
if asyncio.iscoroutine(room_sid):
session_id = await room_sid
else:
session_id = room_sid
except Exception:
session_id = None
session_id = session_id or getattr(ctx.room, "name", "unknown_session")
# sanitize session_id for filename
safe_id = "".join(c if c.isalnum() or c in "-_." else "_" for c in str(session_id))
transcript = session.history.to_dict() if getattr(session, "history", None) else []
os.makedirs("transcripts", exist_ok=True)
fname = os.path.join(
"transcripts",
f"transcript_{safe_id}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
)
payload = {
"session_id": session_id,
"started_at": session_start,
"ended_at": session_end,
"duration_seconds": duration_seconds,
"transcript": transcript,
}
with open(fname, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
print(f"Saved: {fname}")
print(f"Session ID: {session_id}, Duration: {duration_seconds:.2f}s")
Notes:
• Always await async attributes (or detect coroutine) before using their value.
• Sanitize strings used in filenames to remove illegal characters.
• Use ctx.room.name as a reliable synchronous fallback if sid is async or unavailable.
If you want, I can:
• Provide a minimal ready-to-run replacement for your whole file with this fix included, or
• Show a shorter helper function to fetch-and-sanitize the session id. Which do you prefer?cuddly-vr-85751
11/21/2025, 4:08 PMtall-airline-16756
11/21/2025, 4:09 PMfrom dotenv import load_dotenv
load_dotenv()
import time
import json
import os
import asyncio
from datetime import datetime
from typing import List
from livekit.agents import Agent, JobContext, WorkerOptions, cli, function_tool
from livekit.agents.voice import AgentSession
from livekit.plugins import deepgram, groq, cartesia, silero
class SupportAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a helpful support agent. Start by saying your name is Tom.",
stt=deepgram.STT(),
llm=groq.LLM(model="llama-3.1-8b-instant"),
tts=cartesia.TTS(model="sonic-3", voice="e3087ad8-7018-4154-9a87-11577f916cd4"),
vad=silero.VAD.load(),
)
@function_tool()
async def get_free_slots(self, date: str = None) -> List[str]:
return ["10:00 AM", "2:00 PM", "4:30 PM"]
async def _maybe_await(val):
if asyncio.iscoroutine(val):
return await val
return val
def _safe_filename(s):
return "".join(c if c.isalnum() or c in "-_." else "_" for c in str(s))
async def entrypoint(ctx: JobContext):
agent = SupportAgent()
session = AgentSession()
start_ts = None
@session.on("starting")
def _on_start():
nonlocal start_ts
start_ts = time.time()
async def _shutdown():
end_ts = time.time()
duration = end_ts - (start_ts or end_ts)
# try session.id, then ctx.room.sid, then ctx.room.name
sid = None
sid = getattr(session, "id", None) or sid
sid = await _maybe_await(sid) if sid is not None else sid
if not sid:
room_sid = getattr(ctx.room, "sid", None)
room_sid = await _maybe_await(room_sid) if room_sid is not None else room_sid
sid = room_sid or getattr(ctx.room, "name", "unknown_session")
safe_id = _safe_filename(sid)
transcript = session.history.to_dict() if getattr(session, "history", None) else []
os.makedirs("transcripts", exist_ok=True)
fname = os.path.join("transcripts", f"transcript_{safe_id}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json")
with open(fname, "w", encoding="utf-8") as f:
json.dump({
"session_id": str(sid),
"started_at": start_ts,
"ended_at": end_ts,
"duration_seconds": duration,
"transcript": transcript,
}, f, indent=2)
print(f"Saved: {fname}")
print(f"Session ID: {sid}, Duration: {duration:.2f}s")
ctx.add_shutdown_callback(_shutdown)
await session.start(agent=agent, room=ctx.room)
def run():
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="support", port=8081))
if __name__ == "__main__":
run()
Notes:
• _maybe_await handles coroutine or sync attributes safely.
• _safe_filename removes illegal filename chars.
• Transcript uses session.history.to_dict() if available.
• Output saved to ./transcripts/.
Want me to also add per-speaker message counts (very small change)?cuddly-vr-85751
11/21/2025, 4:10 PM{
"session_id": "RM_du55TnvYiW6w",
"started_at": null,
"ended_at": 1763741431.5644953,
"duration_seconds": 0,
"transcript": {
"items": [
{
"id": "item_5bc1b54b81fb",
"type": "message",
"role": "user",
"content": [
"Can you hear me back now at least?"
],
"interrupted": false,
"transcript_confidence": 0.9863281
},
{
"id": "item_da938ad05086",
"type": "message",
"role": "assistant",
"content": [
"Yes, you can hear me back now. I'm Tom, your helpful support agent, and I'll be happy to assist you with any questions or issues you may have. What's on your mind?"
],
"interrupted": false
}
]
}
}tall-airline-16756
11/21/2025, 4:11 PMstarted_at is null because the session start timestamp wasn't set before shutdown. Likely causes and fixes:
1) Cause: starting event handler didn't run before shutdown
• Ensure you register the @session.on("starting") handler before calling await session.start(...). The handler must set the start time synchronously (not async) so it runs immediately.
2) Cause: start handler used an async callback or awaited something (delay)
• Make the starting handler synchronous and simple:
◦ set a plain timestamp like start_ts = time.time() (no await).
3) Reliable alternative: set start time right before starting the session
• Immediately before await session.start(...) assign start_ts = time.time() so you always have a value even if the event isn't emitted.
Minimal fix (apply in your entrypoint):
• Define start_ts = None at top.
• Set start_ts = time.time() directly right before await session.start(agent=agent, room=ctx.room).
• Keep the starting handler as optional backup that also sets it if still None.
That will ensure started_at is populated and duration is computed correctly. Would you like me to patch the small snippet in your file?cuddly-vr-85751
11/21/2025, 4:11 PMtall-airline-16756
11/21/2025, 4:11 PMfrom dotenv import load_dotenv
load_dotenv()
import time
import json
import os
import asyncio
from datetime import datetime
from typing import List
from livekit.agents import Agent, JobContext, WorkerOptions, cli, function_tool
from livekit.agents.voice import AgentSession
from livekit.plugins import deepgram, groq, cartesia, silero
class SupportAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a helpful support agent. Start by saying your name is Tom.",
stt=deepgram.STT(),
llm=groq.LLM(model="llama-3.1-8b-instant"),
tts=cartesia.TTS(model="sonic-3", voice="e3087ad8-7018-4154-9a87-11577f916cd4"),
vad=silero.VAD.load(),
)
@function_tool()
async def get_free_slots(self, date: str = None) -> List[str]:
return ["10:00 AM", "2:00 PM", "4:30 PM"]
async def _maybe_await(val):
if asyncio.iscoroutine(val):
return await val
return val
def _safe_filename(s):
return "".join(c if c.isalnum() or c in "-_." else "_" for c in str(s))
async def entrypoint(ctx: JobContext):
agent = SupportAgent()
session = AgentSession()
# reliable start timestamp (set immediately)
start_ts = time.time()
# also set on "starting" event if available
@session.on("starting")
def _on_start():
nonlocal start_ts
# prefer event time but don't overwrite if already set
start_ts = start_ts or time.time()
async def _shutdown():
end_ts = time.time()
duration = end_ts - (start_ts or end_ts)
# Resolve session id safely (await if coroutine), fallback to room.name
sid = getattr(session, "id", None)
sid = await _maybe_await(sid) if sid is not None else None
if not sid:
room_sid = getattr(ctx.room, "sid", None)
room_sid = await _maybe_await(room_sid) if room_sid is not None else None
sid = room_sid or getattr(ctx.room, "name", "unknown_session")
safe_id = _safe_filename(sid)
transcript = session.history.to_dict() if getattr(session, "history", None) else {"items": []}
os.makedirs("transcripts", exist_ok=True)
fname = os.path.join(
"transcripts",
f"transcript_{safe_id}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
)
payload = {
"session_id": str(sid),
"started_at": start_ts,
"ended_at": end_ts,
"duration_seconds": duration,
"transcript": transcript,
}
with open(fname, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
print(f"Saved: {fname}")
print(f"Session ID: {sid}, Duration: {duration:.2f}s")
ctx.add_shutdown_callback(_shutdown)
await session.start(agent=agent, room=ctx.room)
def run():
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="support", port=8081))
if __name__ == "__main__":
run()
Notes:
• Start time is set immediately before session start to avoid missing it.
• _maybe_await safely awaits coroutine attributes (like ctx.room.sid) if needed.
• Filenames are sanitized to avoid invalid characters.
• Transcript uses session.history.to_dict() when present.
• Adjust paths or storage (DB/API) as required.cuddly-vr-85751
11/21/2025, 4:13 PMtall-airline-16756
11/21/2025, 4:14 PMfrom dotenv import load_dotenv
load_dotenv()
import os
import time
import json
import asyncio
from datetime import datetime
from typing import List
from livekit.agents import Agent, JobContext, WorkerOptions, cli, function_tool
from livekit.agents.voice import AgentSession
from livekit.plugins import deepgram, groq, cartesia, silero
# LiveKit HTTP API client (egress)
from livekit import api
class SupportAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a helpful support agent. Start by saying your name is Tom.",
stt=deepgram.STT(),
llm=groq.LLM(model="llama-3.1-8b-instant"),
tts=cartesia.TTS(model="sonic-3", voice="e3087ad8-7018-4154-9a87-11577f916cd4"),
vad=silero.VAD.load(),
)
@function_tool()
async def get_free_slots(self, date: str = None) -> List[str]:
return ["10:00 AM", "2:00 PM", "4:30 PM"]
async def _maybe_await(val):
if asyncio.iscoroutine(val):
return await val
return val
def _safe_filename(s):
return "".join(c if c.isalnum() or c in "-_." else "_" for c in str(s))
async def entrypoint(ctx: JobContext):
agent = SupportAgent()
session = AgentSession()
# reliable start timestamp
start_ts = time.time()
@session.on("starting")
def _on_start():
nonlocal start_ts
if not start_ts:
start_ts = time.time()
# prepare LiveKit API client for egress
lk_url = os.getenv("LIVEKIT_URL")
lk_key = os.getenv("LIVEKIT_API_KEY")
lk_secret = os.getenv("LIVEKIT_API_SECRET")
lk_api = None
egress_id = None
egress_path = None
if lk_url and lk_key and lk_secret:
lk_api = api.LiveKitAPI(url=lk_url, api_key=lk_key, api_secret=lk_secret)
async def _shutdown():
nonlocal egress_id, lk_api
end_ts = time.time()
duration = end_ts - (start_ts or end_ts)
# resolve session id
sid = getattr(session, "id", None)
sid = await _maybe_await(sid) if sid is not None else None
if not sid:
room_sid = getattr(ctx.room, "sid", None)
room_sid = await _maybe_await(room_sid) if room_sid is not None else None
sid = room_sid or getattr(ctx.room, "name", "unknown_session")
safe_id = _safe_filename(sid)
transcript = session.history.to_dict() if getattr(session, "history", None) else {"items": []}
os.makedirs("transcripts", exist_ok=True)
fname = os.path.join("transcripts", f"transcript_{safe_id}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json")
with open(fname, "w", encoding="utf-8") as f:
json.dump({
"session_id": str(sid),
"started_at": start_ts,
"ended_at": end_ts,
"duration_seconds": duration,
"transcript": transcript,
"audio_file": egress_path,
}, f, indent=2)
print(f"Saved transcript: {fname}")
print(f"Session ID: {sid}, Duration: {duration:.2f}s")
# stop egress if running
if lk_api and egress_id:
try:
await lk_api.egress.stop_egress(egress_id)
print(f"Requested stop for egress {egress_id}")
except Exception as e:
print(f"Failed to stop egress: {e}")
finally:
await lk_api.aclose()
ctx.add_shutdown_callback(_shutdown)
# start egress recording (audio-only mixed file) if API client configured
if lk_api:
try:
out_dir = os.getcwd()
egress_path = os.path.join(out_dir, f"recording_{ctx.room.name}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.ogg")
req = api.RoomCompositeEgressRequest(
room_name=ctx.room.name,
audio_only=True,
file_outputs=[
api.EncodedFileOutput(
file_type=api.EncodedFileType.OGG,
filepath=egress_path,
)
],
)
egress_info = await lk_api.egress.start_room_composite_egress(req)
egress_id = egress_info.egress_id
print(f"Started egress: {egress_id} -> {egress_path}")
except Exception as e:
print(f"Failed to start egress: {e}")
# ensure cleanup later
if lk_api:
await lk_api.aclose()
lk_api = None
# start agent session (blocks until session ends)
await session.start(agent=agent, room=ctx.room)
def run():
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="support", port=8081))
if __name__ == "__main__":
run()
Notes and tips
• Egress saves a mixed audio file (OGG/Opus) containing all participants. File path printed when started.
• Ensure your API key has egress permissions and LIVEKIT_URL is correct (e.g., https://your-livekit-host).
• If you prefer WAV output or different encoding, change EncodedFileType and filepath extension accordingly.
• If you want per-participant raw audio instead of mixed, use AV track capture (more complex).
• The transcript file includes "audio_file" with the egress path for easy lookup.
Do you want a version that:
• records separate per-participant WAV files, or
• uploads recordings to S3 instead of local disk? Sources: Agent insights in LiveKit Cloud | LiveKit docs | Observability data hooks | LiveKit docs | Capturing the First Few Seconds of a Call for Processingcuddly-vr-85751
11/21/2025, 4:25 PMtall-airline-16756
11/21/2025, 4:25 PMcuddly-vr-85751
11/21/2025, 4:39 PMtall-airline-16756
11/21/2025, 4:39 PMctx.dispatch (or ctx.room metadata depending on dispatch). Quick example showing how to parse the JSON metadata you sent:
import json
from livekit.agents import JobContext
async def entrypoint(ctx: JobContext):
# try dispatch metadata first
meta_str = None
if getattr(ctx, "dispatch", None) and getattr(ctx.dispatch, "metadata", None):
meta_str = ctx.dispatch.metadata
# fallback to room metadata if set there
if not meta_str and getattr(ctx.room, "metadata", None):
meta_str = ctx.room.metadata
metadata = {}
if meta_str:
try:
metadata = json.loads(meta_str)
except Exception:
metadata = {"raw": meta_str}
# metadata now contains {"source": "api"} from your CreateAgentDispatchRequest
print("Dispatch metadata:", metadata)
# use metadata in agent logic
source = metadata.get("source")
if source == "api":
await ctx.room.local_participant.publish_data("note", "started by API")
# start your agent session as usual...
Where to look
• ctx.dispatch.metadata — metadata set on the dispatch request (preferred).
• ctx.room.metadata — sometimes metadata is attached to the room; check both.
Tip: send metadata as a JSON string (as you already do) and JSON.parse it in the agent. Would you like a full runnable example that uses the metadata to choose agent behavior?cuddly-vr-85751
11/21/2025, 4:54 PMRoomIO -> AgentSession -> TranscriptSynchronizer -> RoomIO
2025-11-21 222412,629 - DEBUG livekit.agents - using transcript io: AgentSession -> TranscriptSynchronizer -> RoomIO
2025-11-21 222412,657 - DEBUG livekit.agents - start reading stream {"participant": "1b8f868f-35e4-4ba1-bc01-d22c2c97fb8cuser", "source": "SOURCE_MICROPHONE"}tall-airline-16756
11/21/2025, 4:54 PMctx.dispatch.metadata. Room metadata may be on ctx.room.metadata. Log both at start:
meta = getattr(ctx, "dispatch", None) and getattr(ctx.dispatch, "metadata", None)
room_meta = getattr(ctx.room, "metadata", None)
print("dispatch metadata:", meta)
print("room metadata:", room_meta)
4) Common causes why metadata is empty
• The agent was started directly (not via agent_dispatch) so ctx.dispatch is None.
• The dispatch request targeted a different room or failed silently.
• Metadata string was lost/overwritten; check upstream logs for the CreateAgentDispatchRequest response.
5) How to test end-to-end
• From your API: call agent_dispatch.create_dispatch and log the response.
• Immediately after dispatch, open the room and confirm a job appears in the agent runner logs.
• In the agent entrypoint, log ctx.dispatch, ctx.dispatch.metadata, and ctx.room.name.
6) Quick code to robustly read metadata in entrypoint
import json
meta_str = None
if getattr(ctx, "dispatch", None) and getattr(ctx.dispatch, "metadata", None):
meta_str = ctx.dispatch.metadata
elif getattr(ctx.room, "metadata", None):
meta_str = ctx.room.metadata
metadata = {}
if meta_str:
try:
metadata = json.loads(meta_str)
except Exception:
metadata = {"raw": meta_str}
print("resolved dispatch metadata:", metadata)
If you want, I can:
• give a small test snippet to call create_dispatch and print the API response, or
• provide a full agent entrypoint that logs all ctx fields on start to help debug. Which would you prefer?cuddly-vr-85751
11/21/2025, 4:57 PMtall-airline-16756
11/21/2025, 4:58 PMctx.job.metadata (not ctx.dispatch) to read dispatch metadata in your entrypoint. Below is a minimal patch you can drop into your file — it parses JSON metadata safely, logs both job and room metadata for debugging, and continues to start the session as before.
Patch (inside your existing entrypoint, near the top):
# resolve dispatch/job metadata (safe parse)
job_meta_str = getattr(ctx.job, "metadata", None)
room_meta_str = getattr(ctx.room, "metadata", None)
metadata = {}
if job_meta_str:
try:
metadata = json.loads(job_meta_str)
except Exception:
metadata = {"raw_job_metadata": job_meta_str}
elif room_meta_str:
try:
metadata = json.loads(room_meta_str)
except Exception:
metadata = {"raw_room_metadata": room_meta_str}
print("resolved metadata:", metadata)
Place this before creating/starting the session so you can act on metadata (e.g., choose agent behavior). If you still see {} printed, verify your dispatch call set metadata on the CreateAgentDispatchRequest (as a JSON string) and that the dispatch succeeded for the same room the agent joins.
Sources: Job lifecycle | LiveKit docs | External data and RAG | LiveKit Docs | Agent insights in LiveKit Cloud | LiveKit docs | Knowledge Base Content | livekit/livekit_composite | DeepWikicuddly-vr-85751
11/21/2025, 5:06 PMtall-airline-16756
11/21/2025, 5:06 PMcuddly-vr-85751
11/21/2025, 5:07 PMtall-airline-16756
11/21/2025, 5:07 PMcuddly-vr-85751
11/21/2025, 5:07 PMtall-airline-16756
11/21/2025, 5:08 PM<Response>
<Dial>
<Sip username="SIP_USER" password="SIP_PASS">
sip:+YOUR_TWILIO_NUMBER@YOUR_LIVEKIT_SIP_ENDPOINT
</Sip>
</Dial>
</Response>
• SIP_USER and SIP_PASS are credentials you’ll use when creating the inbound trunk in LiveKit.
• YOUR_LIVEKIT_SIP_ENDPOINT is the LiveKit SIP host (e.g., provided by your LiveKit deployment or cloud SIP endpoint).
3) Attach the TwiML bin to your Twilio number
• On the phone number settings → Voice & Fax → "A Call Comes In" → select your TwiML Bin.
4) Create an inbound trunk in LiveKit
• Create a JSON file (inbound-trunk.json):
{
"trunk": {
"name": "twilio-inbound",
"auth_username": "SIP_USER",
"auth_password": "SIP_PASS"
}
}
• Run: lk sip inbound create inbound-trunk.json
• Ensure the SIP credentials match the TwiML Bin values.
5) Add a dispatch rule to route inbound calls to agent rooms
• Create a dispatch-rule.json:
{
"dispatch_rule": {
"rule": {
"dispatchRuleIndividual": {
"roomPrefix": "call-"
}
},
"roomConfig": {
"agents": [
{
"agentName": "my-telephony-agent",
"metadata": "inbound"
}
]
}
}
}
• Run: lk sip dispatch create dispatch-rule.json
• This creates a per-call room (e.g., call-12345) and dispatches your agent named "my-telephony-agent".
6) Ensure your agent is running and named correctly
• Start your agent worker with the same agent name (agent_name or agent metadata).
• In the agent entrypoint, you can read dispatch/job metadata via ctx.job.metadata to handle routing logic.
7) (Optional) Enable recording or egress
• Use LiveKit Room Composite Egress or agent observability to save mixed audio if you need call recordings.
• Configure LiveKit API credentials and start egress when the agent joins the room.
8) Test
• Call your Twilio number. Confirm:
◦ Twilio forwards to the SIP endpoint.
◦ LiveKit creates a room and SIP participant.
◦ Agent runner receives the job (check logs) and joins the room to greet the caller.
Notes & gotchas
• TwiML Bin method is simple but limited (no SIP REFER/outbound calling). For advanced SIP features use Twilio Elastic SIP Trunking.
• Match SIP credentials exactly between TwiML and LiveKit inbound trunk.
• If dispatch metadata is missing in the agent, read ctx.job.metadata or ctx.room.metadata and log both for debugging.
• Ensure UDP/TCP ports and firewall rules allow SIP/RTP to reach your LiveKit SIP endpoint.
If you want, I can:
• produce the exact TwiML with your LiveKit SIP endpoint filled in (share the endpoint),
• give the LiveKit CLI commands tailored to your deployment,
• provide a minimal agent entrypoint snippet that logs ctx.job.metadata and greets the caller. Which would you like? Sources: Inbound calls with Twilio Voice | LiveKit docs | Agents telephony integration | LiveKit Docscuddly-vr-85751
11/21/2025, 5:08 PMtall-airline-16756
11/21/2025, 5:09 PMctx.job.metadata and ctx.room.metadata. Inspect both; Twilio dispatch metadata may appear in job metadata. Log both at start to confirm.
8) Test call
• Call the Twilio number. Verify:
◦ Twilio forwards to your SIP endpoint.
◦ LiveKit creates room (call-...) and SIP participant.
◦ Agent worker receives job (check logs) and joins to greet caller.
9) (Optional) Record audio
• If you need recordings, start Room Composite Egress on agent join (we provided a sample earlier). Ensure LiveKit API creds (LIVEKIT_URL, API_KEY, API_SECRET) are set.
Agent code notes (small changes)
• Make sure your agent name matches dispatch rule.
• Keep your entrypoint metadata parsing (you already have that).
• Optionally, on enter, wait for participant and then generate reply:
await self.session.wait_for_participant() await self.session.generate_reply(instructions="Greet the caller...")
Troubleshooting
• If dispatch metadata is empty: confirm CreateDispatch/dispatch-rule was applied and that the agent was started via dispatch (not manually).
• If SIP auth fails: verify TwiML username/password and LiveKit inbound trunk credentials match.
• If no audio: check firewall/ports and RTP reachability to LiveKit SIP endpoint.
If you want, I can:
• produce the exact TwiML replacing placeholders if you share your LiveKit SIP endpoint and Twilio phone number,
• provide the exact lk CLI commands for your environment,
• add an example that starts egress recording on join.
Which of those would you like next?cuddly-vr-85751
11/21/2025, 5:11 PMtall-airline-16756
11/21/2025, 5:12 PMctx.job.metadata (I can show how to include and read it), or
• Provide the JSON to the agent process at startup (load config file locally)?
Which of these do you want?cuddly-vr-85751
11/21/2025, 5:12 PMtall-airline-16756
11/21/2025, 5:12 PMimport os
import json
from livekit import api
LIVEKIT_URL = os.environ["LIVEKIT_URL"]
LIVEKIT_API_KEY = os.environ["LIVEKIT_API_KEY"]
LIVEKIT_API_SECRET = os.environ["LIVEKIT_API_SECRET"]
async def create_inbound_trunk_and_dispatch():
client = api.LiveKitAPI(url=LIVEKIT_URL, api_key=LIVEKIT_API_KEY, api_secret=LIVEKIT_API_SECRET)
# 1) Create inbound trunk (SIP credentials must match TwiML)
trunk_req = api.CreateInboundTrunkRequest(
trunk=api.Trunk(
name="twilio-inbound",
auth_username="SIP_USER",
auth_password="SIP_PASS",
)
)
trunk = await client.sip.create_inbound_trunk(trunk_req)
print("Created inbound trunk:", trunk.trunk.sid)
# 2) Create dispatch rule that routes inbound calls to rooms with agent "support"
dispatch_rule = api.CreateDispatchRuleRequest(
dispatch_rule=api.DispatchRule(
rule=api.DispatchRuleRule(
dispatchRuleIndividual=api.DispatchRuleIndividual(room_prefix="call-")
),
room_config=api.DispatchRoomConfig(
agents=[
api.DispatchAgentConfig(agent_name="support", metadata=json.dumps({"source":"twilio"}))
]
)
)
)
dr = await client.sip.create_dispatch_rule(dispatch_rule)
print("Created dispatch rule:", dr.dispatch_rule.sid)
await client.aclose()
# To run:
# import asyncio; asyncio.run(create_inbound_trunk_and_dispatch())
B) Minimal agent entrypoint that reads job metadata and starts session
• Place inside your agent file; prints resolved metadata and saves transcript on shutdown.
import os
import time
import json
import asyncio
from datetime import datetime
from livekit.agents import Agent, JobContext, WorkerOptions, cli, function_tool
from livekit.agents.voice import AgentSession
from livekit.plugins import deepgram, groq, cartesia, silero
from typing import List
class SupportAgent(Agent):
def __init__(self):
super().__init__(
instructions="You are a helpful support agent. Start by saying your name is Tom.",
stt=deepgram.STT(),
llm=groq.LLM(model="llama-3.1-8b-instant"),
tts=cartesia.TTS(model="sonic-3", voice="e3087ad8-7018-4154-9a87-11577f916cd4"),
vad=silero.VAD.load(),
)
@function_tool()
async def get_free_slots(self, date: str = None) -> List[str]:
return ["10:00 AM", "2:00 PM", "4:30 PM"]
async def entrypoint(ctx: JobContext):
# Read job metadata (dispatch metadata appears on ctx.job.metadata)
job_meta = getattr(ctx.job, "metadata", None)
room_meta = getattr(ctx.room, "metadata", None)
metadata = {}
if job_meta:
try:
metadata = json.loads(job_meta)
except Exception:
metadata = {"raw_job_metadata": job_meta}
elif room_meta:
try:
metadata = json.loads(room_meta)
except Exception:
metadata = {"raw_room_metadata": room_meta}
print("resolved metadata:", metadata)
agent = SupportAgent()
session = AgentSession()
# Simple start timestamp
start_ts = time.time()
async def on_shutdown():
end_ts = time.time()
duration = end_ts - start_ts
transcript = session.history.to_dict() if getattr(session, "history", None) else {"items": []}
os.makedirs("transcripts", exist_ok=True)
fname = os.path.join("transcripts", f"transcript_{ctx.room.name}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json")
with open(fname, "w", encoding="utf-8") as f:
json.dump({
"session_id": getattr(session, "id", None) or getattr(ctx.room, "name", None),
"started_at": start_ts,
"ended_at": end_ts,
"duration_seconds": duration,
"transcript": transcript,
"metadata": metadata,
}, f, indent=2)
print("Saved:", fname)
ctx.add_shutdown_callback(on_shutdown)
await session.start(agent=agent, room=ctx.room)
def run():
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="support", port=8081))
if __name__ == "__main__":
run()
Notes and troubleshooting
• Ensure your dispatch creation actually returns success. Check logs from the create calls.
• Dispatch metadata is delivered via ctx.job.metadata. If empty, verify the dispatch request included metadata and targeted the same room/agent.
• Run the trunk + dispatch creation before wiring Twilio to the SIP endpoint and before assigning TwiML.
• For Twilio: your TwiML must use the same SIP username/password you created in the inbound trunk.
If you want, I can:
• produce a single script that creates trunk + dispatch, then prints the values to paste into TwiML, or
• show the exact TwiML to paste into Twilio with the created endpoint details. Which do you want?