how to deploey livkeit tserveron vm
# ask-ai
c
how to deploey livkeit tserveron vm
t
Thanks for reaching out, Arun. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I can help—you're asking how to deploy LiveKit server on a VM. Quick clarifying questions so I give exact steps: • Which OS is on the VM (Ubuntu, Debian, CentOS, Amazon Linux)? • Is this VM on a cloud provider (AWS, GCP, Azure, DigitalOcean) or on-prem? • Do you want to use Docker/Docker Compose (recommended) or install binaries directly? • Do you have a domain and TLS certificate, or do you want Caddy/Let's Encrypt to manage HTTPS? • Have you already tried any steps or run into errors? If so, paste the command output or error. If you want a fast path while I wait for details: the usual approach is 1. Generate config locally with the LiveKit generator Docker image. 2. Copy the generated files to the VM (or use the provided cloud-init). 3. Run the included init script to install Docker/Docker Compose and start LiveKit as a systemd service. 4. Ensure DNS points to the VM and open ports 80/443, 7881, 3478/UDP, and 50000–60000/UDP. Tell me your OS/cloud and whether you prefer Docker or native install, and I’ll provide step-by-step commands tailored to your environment. Would you like that? Sources: Deploy to a VM | LiveKit docs
c
on ubunt vm give me full strps
t
Responding to your request for complete step-by-step instructions to deploy LiveKit on an Ubuntu VM. These steps use the Docker-based method (recommended) and the LiveKit config generator to create a ready deployment with Caddy for TLS. Before you begin • You need a domain pointing to your VM’s public IP. • Ensure you can run sudo on the VM. • Open these ports on the VM/network: 80, 443, 7881 (TCP), 3478 (UDP), and 50000–60000 (UDP). 1) Prepare a local machine (or the VM) to generate config • On your local machine (or the Ubuntu VM if you prefer), pull the LiveKit generator image and run it to create configuration files:
Copy code
docker 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):
Copy code
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:
Copy code
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:
Copy code
sudo systemctl start livekit-docker
sudo systemctl enable livekit-docker
• To stop or check status:
Copy code
sudo systemctl stop livekit-docker
sudo systemctl status livekit-docker
5) Verify containers are running • Confirm Docker Compose started the LiveKit containers:
Copy code
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:
Copy code
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:
Copy code
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:
Copy code
sudo journalctl -u livekit-docker -f
• Or inspect container logs:
Copy code
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?
c
from livekit.agents import Agent, JobContext, WorkerOptions, cli from livekit.agents.voice import AgentSession from livekit.plugins import silero, deepgram, groq, cartesia from dotenv import load_dotenv load_dotenv() class SupportAgent(Agent): def __init__(self): super().__init__( instructions="You are a helpful support agent. start saying your name is tom, you need start 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(), ) async def entrypoint(ctx: JobContext): await AgentSession().start(agent=SupportAgent(), room=ctx.room) def run(): cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="support", port=8081)) if name == "__m when i saiy gte free slots it shoul call fucntion
t
You're asking that when the agent hears "get free slots" it should call a function. A few quick clarifying questions so I give the exact code you need: • Do you want the trigger to fire on the agent hearing the phrase from a user speech input (STT) or from a typed chat message? • What should the function do (return available times, call an external API, open a calendar, etc.)? Share the function signature or a short example of the function if you have one. • Should the agent respond verbally after calling the function (e.g., speak the results with TTS) or just log/perform the action? • Do you prefer the agent to match the phrase exactly ("get free slots") or use intent matching / fuzzy matching? If you want a short example now: I can show how to 1) add a simple phrase check in your agent's conversational handler to call a local function and then use the TTS to speak the result, or 2) integrate a function call using a simple intent rule. Which option and trigger type should I show?
c
yes
t
Thanks — I’ll add a concise, runnable example showing how to call a function when the agent hears "get free slots" from speech (STT) and respond via TTS. I’ll adapt your original code and include: • a
@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 AWS
c
full code
t
Below is a complete, runnable example that (A) keeps your agent stack (Deepgram STT, Groq LLM, Cartesia TTS, Silero VAD) and (B) defines a function tool
get_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).
Copy code
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?
c
how function work in agent
t
Regarding "how function work in agent" — here’s a concise explanation tied to your code and how the call flows end-to-end. 1) Registration • You mark a method with
@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?
c
i ena to knwo full cabpalit fo agent like fuicntion toolcals etc
t
You asked for the full capabilities of LiveKit Agents (function tools, function calls, etc.). Below is a concise, organized summary of what agents can do and how to use those features, plus pointers to examples you can ask me to expand into code. Core concepts • Agent: a programmatic participant that joins LiveKit rooms and interacts via voice/text. • AgentSession: runtime that connects an Agent to a LiveKit room and manages audio, STT, LLM, TTS, and events. • Tools (function tools): functions registered on the Agent that the LLM can choose to call during a conversation. Function tools & function calling • Define with
@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 docs
c
is ther enayhtom that when converstion ends i need to get all vonerstiond and how many secondsfrom 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.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): """ 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() session = AgentSession() 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()
t
Yes — you can capture the full conversation transcript and compute total conversation duration when a session ends. Below is a concise, ready-to-use update to your code that: • records session start time, • saves the full transcript at shutdown, • computes total duration in seconds, • and prints (or saves) both results. Paste this into your agent file, replacing your existing `entrypoint`:
Copy code
from 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 docs
c
from dotenv import load_dotenv load_dotenv() import asyncio 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 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() @session.on("conversation_item_added") def _on_item(event): print(f"[LIVE] {event.item.role}: {event.item.text_content}") async def _on_shutdown(): session_end = time.time() duration_seconds = session_end - (session_start or session_end) transcript = session.history.to_dict() tmpdir = os.path.join(os.getcwd(), "transcripts") os.makedirs(tmpdir, exist_ok=True) fname = os.path.join( tmpdir, f"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") 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() mak e more simpel need session id totla dusiton fot he sesion
t
Understood — here’s a much simpler version that only captures the session ID, total duration (seconds), and saves the transcript when the session ends. Copy-paste into your file and run.
Copy code
from 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?
c
ekit.agents - job exiting {"reason": "", "tid": 36848, "job_id": "AJ_eY5QBodhMSUD"} 2025-11-21 213803,538 - ERROR livekit.agents - error while shutting down the job Traceback (most recent call last): File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\ipc\job_proc_lazy_main.py", line 298, in _run_job_task await asyncio.gather(*shutdown_tasks) File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\job.py", line 234, in wrapper await callback() # type: ignore ^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\agents\support.py", line 60, in _on_shutdown with open(fname, "w") as f: ^^^^^^^^^^^^^^^^ OSError: [Errno 22] Invalid argument: 'transcripts\\transcript_<coroutine object Room.sid at 0x0000021C01A45780>_20251121_160803.json' 2025-11-21 213803,540 - DEBUG livekit.agents - http_session(): closing the httpclient ctx
t
The error means you used a coroutine object as part of the filename (e.g.,
ctx.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:
Copy code
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?
c
ful fixed code with less code
t
Understood — here’s a minimal, fixed version of your agent file. It safely obtains a session identifier (awaiting async properties if needed), records start/end times, saves a sanitized transcript filename, and avoids the coroutine-in-filename error. Save as support.py and run.
Copy code
from 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)?
c
Copy code
{
  "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
      }
    ]
  }
}
t
Thanks — the JSON shows
started_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?
c
full fixed code
t
Save this as support.py — minimal, fixed, and complete. It sets start time reliably, safely obtains/sanitizes a session id, records end time, duration, and saves the transcript to ./transcripts/*.json.
Copy code
from 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.
c
from 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() can i also record audio of convertions
t
Understood — below is a minimal, complete agent file that: • records start/end times and session ID, • saves transcript and metadata, • starts a LiveKit Room Composite Egress to record mixed audio to a file, • stops egress on shutdown. Requirements: • set LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET in your environment (.env) • livekit-agents and livekit-server SDKs installed with egress support • egress API key permissions Save as support.py and run.
Copy code
from 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 Processing
c
whichj is good for agent build ing pyhton or nodjs
t
Both Python and Node.js are good choices for building LiveKit agents. Which is best depends on your priorities — here’s a concise comparison to help you choose. Python • Strengths: concise syntax, mature ML/AI ecosystem (LLM tooling, numpy/pandas), easier for rapid prototyping and data-heavy logic. • Async model: asyncio is solid for I/O; LiveKit Agents Python SDK provides full agent features (function tools, MCP, tasks, testing utilities). • Ecosystem: strong for integrations with ML models, RAG, and server-side processing. • Best if: your agent relies on heavy ML/AI, academic/analysis workflows, or your team is Python-first. Node.js • Strengths: excellent real‑time and WebRTC ecosystem, low-latency I/O, easier to integrate with browser frontends and client-side RPCs. • Async model: event-driven JS fits realtime use cases naturally; LiveKit Agents for Node provides comparable features (tools, handoffs, TTS/ STT plugins). • Ecosystem: rich JS tooling, native familiarity for full‑stack JS teams, straightforward frontend <-> agent integration. • Best if: you need tight frontend integration, low-latency streaming, or your stack is JavaScript/TypeScript. Other practical factors • Team skills: pick the language your team knows best to move faster. • Libraries & integrations: choose the language with easier access to the external APIs you’ll use (e.g., specific SDKs, cloud libs). • Deployment: both deploy easily (containers, serverless, VMs). Node is often lighter for single-threaded low-latency tasks; Python is fine for CPU-bound ML if you provide adequate resources. Recommendation • If your project centers on LLM-heavy logic, RAG, or ML tooling → Python. • If you need close browser integration, minimal latency streaming, or you’re full‑stack JS → Node.js. I can: • provide a minimal starter example in Python or Node.js for a LiveKit voice agent, • map feature parity (which SDK features differ), • help you pick based on a short description of your use case. Which would you like?
c
@router.post("/connect-agent/{agent_type}/{room_name}") async def connect_agent(agent_type: str = Path(..., example="support"), room_name: str = Path(..., example="room_support")): if agent_type not in {"support", "billing"}: raise HTTPException(400, "agent_type must be 'support' or 'billing'") async with api.LiveKitAPI( url=LIVEKIT_URL, api_key=LIVEKIT_API_KEY, api_secret=LIVEKIT_API_SECRET, ) as client: try: await client.agent_dispatch.create_dispatch( api.CreateAgentDispatchRequest( agent_name=agent_type, room=room_name, metadata=json.dumps({"source": "api"}), ) ) except Exception as e: raise HTTPException(500, f"Failed to dispatch agent: {e}") return {"room": room_name, "agent": agent_type} hwo to get thsi metadat in agent
t
You can read the dispatch metadata from the JobContext passed into your agent entrypoint — it’s available on
ctx.dispatch
(or
ctx.room
metadata depending on dispatch). Quick example showing how to parse the JSON metadata you sent:
Copy code
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?
c
2025-11-21 222411,544 - INFO livekit.agents - initializing job runner {"tid": 20348} 2025-11-21 222411,545 - DEBUG asyncio - Using proactor: IocpProactor 2025-11-21 222411,545 - INFO livekit.agents - job runner initialized {"tid": 20348, "elapsed_time": 0.0} Dispatch metadata: {} 2025-11-21 222412,050 - DEBUG livekit.agents - input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"]} 2025-11-21 222412,054 - DEBUG livekit.agents - http_session(): creating a new httpclient ctx on_enter <__mp_main__.SupportAgent object at 0x000002C9762A5610> 2025-11-21 222412,625 - DEBUG livekit.agents - start reading stream {"participant": "1b8f868f-35e4-4ba1-bc01-d22c2c97fb8cuser", "source": "SOURCE_MICROPHONE"} 2025-11-21 222412,629 - DEBUG livekit.agents - using audio io:
RoomIO
->
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"}
t
You're seeing empty dispatch metadata. Likely reasons and quick fixes: 1) Verify your dispatch request sets metadata • Ensure you send a JSON string in CreateAgentDispatchRequest like you showed: metadata=json.dumps({"source":"api"}) 2) Confirm the dispatch API call succeeded and targeted the same room name the agent joins • Check the client call returned without error and the room name matches the one the agent sees (ctx.room.name). 3) Check where metadata appears at runtime • Dispatch metadata is available on
ctx.dispatch.metadata
. Room metadata may be on
ctx.room.metadata
. Log both at start:
Copy code
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
Copy code
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?
c
from 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(), ) async def on_enter(self) -> None: print("on_enter", self) await self.session.generate_reply(instructions="Greet the user and ask how you can help them.") @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()metsta data cnot ocming fchecl lates t docs
t
Use
ctx.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):
Copy code
# 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 | DeepWiki
c
how tp setup telpehony for this agent
t
I can guide you. Quick questions to tailor steps: • Do you want inbound calls (customers call a number), outbound calls (agent dials a number), or both? • Do you prefer using LiveKit Phone Numbers (simpler) or a SIP provider like Twilio/Plivo? • Do you want mixed/multi-party recordings or per-participant audio? • Which region/provider will you use (some regions require extra config)? Pick answers to the above and I’ll give a step‑by‑step setup for your preferred path (LiveKit Phone Numbers or Twilio SIP) and a minimal code example to connect calls to your agent. Sources: Agents telephony integration | LiveKit Docs | Inbound calls with Twilio Voice | LiveKit docs | Create and configure a Plivo SIP trunk | LiveKit docs
c
inbound call
t
Do you want to use LiveKit Phone Numbers (easier) or a third‑party SIP provider (Twilio/Plivo)? Also tell me your region (country) and whether you need recordings. I’ll give step‑by‑step inbound setup for that choice.
c
sorry oubbut wirrh twilio
t
You're set to use Twilio for inbound calls. Here’s a concise, actionable checklist plus minimal TwiML and LiveKit config snippets to get an inbound call routed to your agent. 1) Purchase a Twilio phone number • In the Twilio Console, buy a number that supports Voice. 2) Create TwiML to forward calls to LiveKit via SIP • In Twilio Console → TwiML Bins, create a bin with this TwiML (replace placeholders):
Copy code
<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):
Copy code
{
  "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:
Copy code
{
  "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 Docs
c
from 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(), ) async def on_enter(self) -> None: print("on_enter", self) await self.session.generate_reply(instructions="Greet the user and ask how you can help them.") @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): 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) 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() setwup teilio with this
t
I'll give step-by-step instructions to connect Twilio inbound calls to your existing Python agent, plus the small agent changes you need. 1) Create SIP credentials (username/password) • Pick a SIP username and password (e.g., SIP_USER / SIP_PASS). You will use these in TwiML and LiveKit. 2) TwiML Bin in Twilio • Console → Develop → TwiML Bins → Create. • TwiML (replace placeholders): <Response> <Dial> <Sip username="SIP_USER" password="SIP_PASS"> sip:+YOUR_TWILIO_NUMBER@YOUR_LIVEKIT_SIP_ENDPOINT </Sip> </Dial> </Response> • YOUR_LIVEKIT_SIP_ENDPOINT: your LiveKit SIP host (from LiveKit cloud/instance). Use the domain provided by LiveKit SIP. 3) Attach TwiML Bin to your Twilio number • Console → Phone Numbers → Manage → pick number → Voice & Fax → "A Call Comes In" → select your TwiML Bin. 4) Create inbound trunk in LiveKit • Create JSON (inbound-trunk.json): { "trunk": { "name": "twilio-inbound", "auth_username": "SIP_USER", "auth_password": "SIP_PASS" } } • Run: lk sip inbound create inbound-trunk.json • Ensure SIP_USER/SIP_PASS match the TwiML Bin. 5) Add a dispatch rule to route calls to agent rooms • dispatch-rule.json: { "dispatch_rule": { "rule": { "dispatchRuleIndividual": { "roomPrefix": "call-" } }, "roomConfig": { "agents": [{ "agentName": "support", "metadata": "{\"source\":\"twilio\"}" }] } } } • Run: lk sip dispatch create dispatch-rule.json • This creates per-call rooms (call-*) and dispatches agent named "support". Adjust agentName to match your worker. 6) Ensure agent worker is running with that agent name • Start your worker so it listens for dispatches as agent "support" (your cli.run_app WorkerOptions agent_name should match). 7) Read dispatch metadata in your entrypoint • You already parse
ctx.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?
c
how ro connect to the agent ths json file
t
Do you mean one of these? • Apply the dispatch JSON (dispatch-rule.json) to LiveKit so calls route to the agent (I can show lk CLI or API steps), • Send metadata in the JSON to the agent so it’s available in
ctx.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?
c
code
t
Below are two concise Python examples you can use to (A) create the inbound trunk and dispatch rule programmatically via the LiveKit HTTP API, and (B) an agent entrypoint that reads the job metadata and starts the agent session. Use these together to create the trunk/dispatch and ensure the agent receives metadata. A) Create inbound trunk + dispatch rule via LiveKit API (Python) • Installs: pip install livekit-server-sdk • Replace LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET with your env vars.
Copy code
import 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.
Copy code
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?