I've created an agent and am trying to do a phone ...
# ask-ai
s
I've created an agent and am trying to do a phone call using the agent.
Copy code
def dispatch_agent(
        self,
        agent_name: str,
        room_name: str,
        metadata: dict[str, Any] | None = None,
        room_details: RoomDetails | None = None,
    ) -> dict[str, Any]:
        """
        Dispatch an agent to a LiveKit room.

        This method calls the LiveKit Agent Dispatch API to create an agent instance
        in a room. It replicates the behavior of:
        await lkapi.agent_dispatch.create_dispatch(CreateAgentDispatchRequest(...))

        Args:
            agent_name: The name of the agent to dispatch (e.g., "my-telephony-agent")
            room_name: The name of the LiveKit room (should be unique per call)
            metadata: Optional metadata dict to pass to the agent
                     (e.g., {"phone_number": "+15105550123"})

        Returns:
            dict: Response from the LiveKit Agent Dispatch API

        Raises:
            ValueError: If required credentials are missing
            HTTPError: If the API request fails
        """
        # Validate credentials are loaded
        if not self.api_key or not self.api_secret:
            log.error("LiveKit credentials not properly loaded. Check AWS Secrets Manager configuration.")
            raise ValueError("LiveKit API credentials are missing or empty")

        # Create access token with agent dispatch permissions
        now = int(time.time())
        exp = now + 300  # token valid 5 min

        claims = {
            "iss": self.api_key,
            "video": {
                "roomCreate": True,
                "room": room_name,
            },
            "agent": {
                "dispatch": True,
            },
            "iat": now,
            "nbf": now,
            "exp": exp,
        }
        room_config = {
            "agents": [
                {
                    "agentName": room_details.agent_name,
                    "metadata": json_utils.dumps(room_details.room_metadata),
                }
            ],
            "departureTimeout": room_details.departure_timeout_in_seconds,
        }
        claims["roomConfig"] = room_config

        token = jwt.encode(
            claims,
            self.api_secret,
            algorithm="HS256",
            headers={"typ": "JWT"}
        )

        log.info(f"Generated JWT token for agent dispatch. Issuer: {self.api_key}")

        # Convert ws/wss → http/https
        http_url = self.livekit_url.replace("wss://", "https://").replace("ws://", "http://")

        # Agent dispatch endpoint
        url = f"{http_url}/twirp/livekit.Agent/CreateDispatch"

        payload = {
            "agentName": agent_name,
            "room": room_name,
            "metadata": json_utils.dumps(metadata or {}),
        }

        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        }

        log.info(f"Dispatching agent '{agent_name}' to room '{room_name}'")
        log.debug(f"Request URL: {url}")
        log.debug(f"Request payload: {payload}")

        try:
            response = requests.post(url, json=payload, headers=headers, timeout=30)
            response.raise_for_status()
            log.info(f"Successfully dispatched agent '{agent_name}' to room '{room_name}'")
            print(response.text)
            return response.text
        except requests.exceptions.HTTPError as e:
            log.error(f"Failed to dispatch agent: {e.response.status_code} {e.response.reason}")
            log.error(f"Response body: {e.response.text}")
            log.debug(f"API Key used: {self.api_key}")
            log.debug(f"LiveKit URL: {http_url}")
            raise
        except requests.exceptions.RequestException as e:
            log.exception(f"Request failed while dispatching agent: {e}")
            raise
Then The agent code is:
Copy code
class PhoneAssistant(Agent):
    def __init__(
        self,
        system_instruction: str,
        participant: rtc.RemoteParticipant | None = None,
        dial_info: dict[str, Any] | None = None,
    ) -> None:
        super().__init__(
            instructions=system_instruction,
        )
        self.participant = participant
        self.dial_info = dial_info or {}

    def set_participant(self, participant: rtc.RemoteParticipant) -> None:
        """Set the remote participant for phone calls"""
        self.participant = participant

    @function_tool
    async def end_call(self, context: RunContext[None]) -> None:
        """ "
        Call this function to end the current conversation and deliver your farewell message when AT LEAST ONE OF these conditions is met:
        1. The main task/request has been successfully completed and the user has confirmed they are satisfied
        2. The conversation has reached a clear and natural conclusion with mutual agreement
        3. The user has explicitly indicated they want to end the conversation
        Before calling this function:
        1. Always confirm all user queries are fully addressed
        2. Always ask the user if you can help them with anything else
        Do NOT call end_call function if:
        1. There are pending user questions or requests
        2. The user seems unsatisfied with the current resolution
        3. The conversation is still actively progressing
        """
        try:
            room = get_job_context().room
            end_call_data = {"type": "end_call_tool", "timestamp": time.time()}
            data_packet = json.dumps(end_call_data).encode("utf-8")
            await room.local_participant.publish_data(data_packet)
            logger.info("Trying to disconnect room")
            await room.disconnect()
        except Exception as e:
            logger.error(f"Error in end_call tool: {e}")
            raise ToolError(f"Unable to end call: {e!s}") from e


def prewarm(proc: JobProcess) -> None:
    proc.userdata["vad"] = silero.VAD.load()


async def entrypoint(ctx: JobContext) -> None:
    await ctx.connect()
    print(f"ctx.job.metadata: {ctx.job}")

    ctx.log_context_fields = {
        "room": ctx.room.name,
    }

    # Parse metadata
    metadata_dict = json.loads(ctx.job.metadata) if ctx.job.metadata else {}
    metadata = Metadata.model_validate(metadata_dict)

    logger.info(f"Metadata: {metadata}")

    group_id = metadata.conversation_data.group_id
    conversation_id = metadata.conversation_data.conversation_id

    # Prepare dial_info for outbound calls
    dial_info = {
        "phone_number": metadata.conversation_data.phone_number,
    }

    # System instruction
    system_instruction = (
        CUSTOM_LLM_SYSTEM_INSTRUCTION
        if metadata.conversation_data.llm_type == "custom_llm"
        else metadata.conversation_data.system_instruction
    )

    # Create assistant
    assistant = PhoneAssistant(
        system_instruction=system_instruction,
        dial_info=dial_info,
    )

    if metadata.conversation_data.llm_type == "direct_llm":
        llm = openai.LLM(model="gpt-4.1-mini")
    elif metadata.conversation_data.llm_type == "custom_llm":
        llm = openai.LLM(
            base_url=metadata.service_endpoints.chat_completion_url,
            metadata=metadata.conversation_data.model_dump(),
        )

    session: AgentSession[None] = AgentSession(
        llm=llm,
        stt=openai.STT(model="gpt-4o-transcribe"),
        tts=metadata.conversation_data.voice_id,
        turn_detection=MultilingualModel(),
        vad=ctx.proc.userdata["vad"],
        preemptive_generation=True,
        use_tts_aligned_transcript=True,
    )

    # sometimes background noise could interrupt the agent session, these are considered false positive interruptions
    # when it's detected, you may resume the agent's speech
    @session.on("agent_false_interruption")
    def _on_agent_false_interruption(ev: AgentFalseInterruptionEvent) -> None:
        logger.info("false positive interruption, resuming")
        session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)


    # Handle outbound phone call
    logger.info(f"Setting up outbound call to {dial_info['phone_number']}")

    phone_number = dial_info["phone_number"]
    participant_identity = phone_number

    # Create session task to start before dialing
    session_started = asyncio.create_task(
        session.start(
            agent=assistant,
            room=ctx.room,
            room_input_options=RoomInputOptions(
                noise_cancellation=noise_cancellation.BVCTelephony(),
                close_on_disconnect=False,
            ),
        )
    )

    # Create SIP participant (dial out)
    try:
        logger.info(f"Creating SIP participant for {phone_number}")
        await ctx.api.sip.create_sip_participant(
            api.CreateSIPParticipantRequest(
                room_name=ctx.room.name,
                sip_trunk_id=sip_outbound_trunk_id,
                sip_call_to=phone_number,
                participant_identity=participant_identity,
                wait_until_answered=True,
            )
        )

        # Wait for session and participant
        await session_started
        participant = await ctx.wait_for_participant(identity=participant_identity)
        logger.info(f"Participant joined: {participant.identity}")
        assistant.set_participant(participant)

    except api.TwirpError as e:
        logger.error(
            f"Error creating SIP participant: {e.message}, "
            f"SIP status: {e.metadata.get('sip_status_code')} "
            f"{e.metadata.get('sip_status')}"
        )
        ctx.shutdown()
        return


    # Have the agent say the initial message aloud (if metadata was retrieved)
    initial_message = (
        metadata.conversation_data.initial_message
        if metadata.conversation_data.initial_message
        else "Hello! I'm your AI assistant. How can I help you today?"
    )
    await session.say(initial_message, allow_interruptions=False)

    async def post_call_hook() -> None:
        transcript_data = session.history.to_dict(
            exclude_timestamp=False, exclude_function_call=False
        )
        chat_context = ChatContext.from_dict(transcript_data)

        event_data = Event(
            event_type="post_call",
            conversation_id=conversation_id,
            group_id=group_id,
            event_data=PostCallEvent(
                transcript=chat_context.items,
            ),
        )

        await send_webhook_event(
            "https://asinghal.dev2.eightfold.ai/api/voice_agent/conversation-events",
            event_data.model_dump(),
        )
        logger.info(f"Post call hook sent for {ctx.room.name}")

    ctx.add_shutdown_callback(post_call_hook)


if __name__ == "__main__":
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            prewarm_fnc=prewarm,
            agent_name="agent_conversation_phone_kit",
        )
    )
But the worker is not getting the call
t
Thanks for reaching out, Anuj. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Are you using SIP integration for this setup? If so, have you had a chance to configure a dispatch rule with the correct agentName that matches your worker configuration? Also, if you could share any specific error messages or logs from the agent or server, that would really help us understand what might be going on. I'm here to help you through this! Sources: Agents telephony integration | LiveKit docs | SIP dispatch rule | LiveKit docs | Troubleshooting & Common Issues | livekit/livekit_composite | DeepWiki | LiveKit Docs | README.md
s
I'm using SIP. I'm not getting any error messages on agent dispatch api call. I'm not getting any logs on my agent worker when agent dispatch happens.
t
Let's explore some possible reasons why your agent worker might not be receiving logs or jobs when using SIP integration and the agent dispatch API. I’m here to help you work through this step by step: • Agent Worker Registration: First, please make sure your agent worker is properly registered and ready to receive jobs. You can check this easily by running the command
lk agent status
to see the worker's current status. • Dispatch Configuration: If you're using explicit dispatch, double-check that the
agent_name
in your dispatch rule exactly matches the worker's configuration. For SIP inbound calls, it’s important that the dispatch rule includes the correct
room_config.agents
field. • Authentication and Permissions: It’s also a good idea to verify that the worker has the right claims, like
claims.Video.Agent
. Without these, the worker might not be authorized to receive jobs. • Log Visibility: Keep in mind, the
lk agent logs
command shows logs only from the latest running worker instance. If your worker isn’t the newest instance, its logs might not appear. Using an external logging service could help capture all logs comprehensively. • Server Version: Lastly, if your LiveKit server version is older than 1.6.2, there’s a known issue that might be preventing agent jobs from launching. Updating to the latest version might resolve this. To move forward smoothly, could you please confirm the following for me? • Is the worker properly registered and showing up in the agent status? • Does the dispatch rule correctly match the worker’s
agent_name
? • Are you running the latest LiveKit server version? Sources: README.md | Troubleshooting & Common Issues | livekit/livekit_composite | DeepWiki | Agent dispatch | LiveKit Docs | pkg/service/agentservice.go | Log collection | LiveKit docs
s
I have multiple agents how to check for each?
t
I'm here to help you check the status and logs for multiple agents in LiveKit. Let's walk through the steps together: • Status Monitoring: ◦ You can start by using
lk agent list
to view all agents along with their basic status. ◦ If you're interested in specific agents, try
lk agent list --id agent-1 --id agent-2
to narrow it down. ◦ For a more detailed look at an individual agent's status, use
lk agent status --id <agent-id>
. This gives you deeper insights. • Log Collection: ◦ To stream logs from the latest instance of a single agent, simply run
lk agent logs --id <agent-id> --log-type=deploy
. This helps you see recent deployment activity. ◦ If you want to check build logs, use
lk agent logs --id <agent-id> --log-type=build
. ◦ Just a quick note: the CLI streams logs only from the newest worker instance of one agent at a time. So, if you need logs from multiple agents, you’ll want to check them one by one or consider using an external logging service for convenience. • Comprehensive Log Collection: For thorough log coverage across all instances and agents, I recommend setting up log forwarding to external services like Datadog, CloudWatch, Sentry, or New Relic. This way, you get logs from all running instances, enjoy long-term storage, and benefit from advanced monitoring features. Sources: Community & Support | livekit/livekit_composite | DeepWiki | cmd/lk/agent.go | Deploying to production | LiveKit Docs | Log collection | LiveKit docs | CLI Tools & Token Management | livekit/livekit_composite | DeepWiki
s
it's only listing one agent, how to do do cloud deploy of an agent that's in a particular file? right now i do local deploys
t
I'm happy to help you deploy your LiveKit agent to the cloud! To get this done smoothly, it's important to organize your files within a proper directory structure because LiveKit works with directory-based deployments rather than single files. Here's a friendly step-by-step guide to walk you through it: • Prepare the Directory: ◦ Start by creating a directory (for example,
my-agent/
) and place your main agent file (like
my_agent.py
) inside it. ◦ Make sure your directory includes these essential files: ▪︎ `my_agent.py`: This is your agent code. ▪︎ `Dockerfile`: This handles the build configuration (don’t worry if it’s not there yet—it will be auto-generated). ▪︎ `livekit.toml`: Your agent configuration file, which gets created during the first deployment. ▪︎
requirements.txt
or `package.json`: To list your dependencies. ▪︎ `.dockerignore`: To specify files you want to exclude. • Deploy the Directory: ◦ Once everything is in place, simply run
lk agent deploy ./my-agent
to deploy your directory. ◦ If this is your very first deployment, start with
lk agent create ./my-agent
to generate the
livekit.toml
file. • Inject Secrets: ◦ If you need to include any secrets, you can use the
--secrets
or
--secrets-file
flags during deployment. For example:
lk agent deploy ./my-agent --secrets OPENAI_API_KEY=sk-xxx
. • Automate Deployment: ◦ For a smoother workflow, especially if you’re using CI/CD, consider setting up GitHub Actions to automatically deploy your directory whenever you make changes. Once your directory is all set up, deploying to the cloud with the LiveKit CLI becomes straightforward. If you’d like, I’m here to help you with organizing your directory or setting up those configuration files—just let me know! Sources: cmd/lk/agent.go | pkg/cloudagents/client.go | Agent deployment CLI reference | LiveKit Docs | CLI Tools & Token Management | livekit/livekit_composite | DeepWiki | Deploying to production | LiveKit Docs
s
i'm doing a dev deploy, so i don't have an agent_id to use. how do i debug my issue
t
To help you debug your LiveKit agent during development deployment without an
agent_id
, here are some friendly steps you can try: • Local Development Mode: ◦ Try running your agent locally with hot reloading using
python myagent.py dev
. This way, you can test and make changes easily without the need to deploy to the cloud. ◦ You can also use
python myagent.py console
to test your agent right in the terminal with local audio input/output. It’s a great way to quickly check things out. • Interactive Agent Selection: ◦ If you’ve deployed agents but aren’t sure about the
agent_id
, just run
lk agent list
to see all the agents available to you. ◦ When you run commands like
lk agent status
or
lk agent logs
without specifying an
agent_id
, the CLI will kindly prompt you to pick from the agents it finds. This makes it easier to select the right one. • Debugging Deployment Issues: ◦ To get insights on build problems, check the build logs with
lk agent logs --log-type=build
. ◦ For runtime issues, keep an eye on the logs using
lk agent logs --log-type=deploy
. These logs can be really helpful in spotting what’s going on. • Creating Configuration: ◦ If you want to connect to an existing agent, you can create a
livekit.toml
file for your project by running
lk agent config
. This sets things up nicely for you. I hope these tips make debugging your agent a smoother experience. If you run into any bumps or have more questions, please don’t hesitate to ask—I’m here to help! Sources: README.md | autocomplete/fish_autocomplete | Agent deployment CLI reference | LiveKit Docs
s
Copy code
# Create access token with agent dispatch permissions
        now = int(time.time())
        exp = now + 300  # token valid 5 min

        claims = {
            "iss": self.api_key,
            "video": {
                "roomCreate": True,
                "room": room_name,
            },
            "agent": {
                "dispatch": True,
            },
            "iat": now,
            "nbf": now,
            "exp": exp,
        }
        room_config = {
            "agents": [
                {
                    "agentName": room_details.agent_name,
                    "metadata": json_utils.dumps(room_details.room_metadata),
                }
            ],
            "departureTimeout": room_details.departure_timeout_in_seconds,
        }
        claims["roomConfig"] = room_config

        token = jwt.encode(
            claims,
            self.api_secret,
            algorithm="HS256",
            headers={"typ": "JWT"}
        )

        log.info(f"Generated JWT token for agent dispatch. Issuer: {self.api_key}")

        # Convert ws/wss → http/https
        http_url = self.livekit_url.replace("wss://", "https://").replace("ws://", "http://")

        # Agent dispatch endpoint
        url = f"{http_url}/twirp/livekit.Agent/CreateDispatch"

        payload = {
            "agentName": agent_name,
            "room": room_name,
            "metadata": json_utils.dumps(metadata or {}),
        }

        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        }

        log.info(f"Dispatching agent '{agent_name}' to room '{room_name}'")
        log.debug(f"Request URL: {url}")
        log.debug(f"Request payload: {payload}")

        try:
            response = requests.post(url, json=payload, headers=headers, timeout=30)
            response.raise_for_status()
            log.info(f"Successfully dispatched agent '{agent_name}' to room '{room_name}'")
            print(response.text)
            return response.text
Is this not the right way to dispatch the agent?
t
Thank you for sharing the code snippet for dispatching an agent to a LiveKit room! It looks like you’re on the right track and following the documented method for explicit agent dispatch using the Agent Dispatch API. Let’s walk through some important points together: • JWT Token Creation: Your code generates a JWT token with the necessary claims, including
roomCreate
and
dispatch
permissions, which is exactly what’s needed for agent dispatch. • Room Configuration: The
roomConfig
field is included properly in the claims, specifying the agent and metadata—great job here! • API Endpoint: You’ve correctly converted the WebSocket URL to an HTTP/S URL for the Twirp-based RPC service, which is essential for control plane operations. • Dispatch Request: The payload includes the
agentName
,
room
, and optional metadata, and the request is sent to the right endpoint. If you’re finding that the dispatch isn’t working quite as expected, here are a few things you might want to double-check: • Make sure the
agentName
exactly matches the name of a registered agent worker. • Take a look at the logs of the agent worker to confirm it’s running and ready to accept jobs. • Verify that the JWT token is properly signed and includes all the required claims. • Confirm that the LiveKit server URL and API credentials are correct. Please don’t hesitate to reach out if you’d like me to help you dig deeper into this or if you have any other questions. I’m here to help! Sources: Agent dispatch | LiveKit Docs | livekit-api/livekit/api/agent_dispatch_service.py | packages/livekit-server-sdk/src/AgentDispatchClient.ts | examples/agent_dispatch/src/main.rs
s
all the points you mentioned are already taken care of yet I'm not getting anything on the local agent.
t
Even when the dispatch API call goes through successfully, there are a few reasons why your agent might not be receiving the job. Let’s walk through some common causes and how you can troubleshoot them: • No Available Workers: First, double-check that your agent workers are up and running, and that they’re registered with the correct
agent_name
matching your dispatch request. You can use
lk agent status
to see if workers are available. • Agent Name and Job Type Mismatch: Make sure the worker is set up to handle the specific job type you’re dispatching—whether that’s room, publisher, or participant jobs. • Worker Registration Issues: It’s important to confirm that workers are properly registering with the LiveKit server. Keep an eye on the logs for any registration events. • Cache Invalidation: The system uses caching to track worker availability. Sometimes, if the cache is outdated, the dispatcher might not see available workers. Restarting the worker or server can often refresh this cache. • Assignment Timeout: Check your agent logs for any assignment timeout errors. This usually means the agent accepted the job but didn’t get the assignment within the expected time. • Job Rejection by Worker: Verify that your worker’s
job_request_fnc
is properly implemented to accept jobs. If it doesn’t respond, the job gets rejected automatically. I hope this helps you narrow things down! Feel free to check your LiveKit server logs for details about worker availability or job rejections, and confirm your agent worker is running and configured correctly. If you’d like, I’m here to help you step through any part of this—just let me know! Sources: livekit-agents/livekit/agents/worker.py | pkg/agent/worker.go | Operational Best Practices | livekit/livekit_composite | DeepWiki | agents/src/_exceptions.ts
s
uv run python src/agents/phone_kit_agent/phone_kit.py dev warning:
VIRTUAL_ENV=/Users/asinghal/Desktop/work/vscode/venv
does not match the project environment path
.venv
and will be ignored; use
--active
to target the active environment instead
2025-11-12 120456,082 - DEBUG asyncio - Using selector: KqueueSelector 2025-11-12 120456,083 - DEV livekit.agents - Watching /Users/asinghal/Desktop/work/livekit-agents/src/agents/phone_kit_agent 2025-11-12 120457,393 - DEBUG asyncio - Using selector: KqueueSelector 2025-11-12 120457,402 - INFO livekit.agents - starting worker {"version": "1.2.15", "rtc-version": "1.0.16"} 2025-11-12 120457,402 - INFO livekit.agents - starting inference executor 2025-11-12 120457,407 - INFO livekit.agents - initializing process {"pid": 55301, "inference": true} 2025-11-12 120458,732 - DEBUG livekit.agents - initializing inference runner {"runner": "lk_end_of_utterance_multilingual", "pid": 55301, "inference": true} None of PyTorch, TensorFlow >= 2.0, or Flax have been found. Models won't be available and only tokenizers, configuration and file/data utilities can be used. 2025-11-12 120501,024 - DEBUG livekit.agents - inference runner initialized {"runner": "lk_end_of_utterance_multilingual", "elapsed_time": 2.2916253750008764, "pid": 55301, "inference": true} 2025-11-12 120501,025 - INFO livekit.agents - process initialized {"pid": 55301, "inference": true, "elapsed_time": 3.62} 2025-11-12 120501,024 - DEBUG asyncio - Using selector: KqueueSelector {"pid": 55301, "inference": true} 2025-11-12 120501,126 - INFO livekit.agents - registered worker {"id": "AW_Ewnvprxx3ZXt", "url": "wss://air-76v7fg9o.livekit.cloud", "region": "India South", "protocol": 16}
t
The warning about VIRTUAL_ENV mismatch indicates that the Python virtual environment you're using (/Users/asinghal/Desktop/work/vscode/venv) doesn't quite match the expected path (.venv). Are you currently running the agent inside a virtual environment, and if so, is it activated properly? Also, could you let me know if you're using Docker or any custom deployment setup? Understanding this will really help us work together to resolve the issue smoothly. Sources: Automation & Knowledge Management Tools | livekit/livekit_composite | DeepW...
s
I've deployed the agent on livekit server. These are the logs: {"message": "starting worker", "level": "INFO", "name": "livekit.agents", "version": "1.2.15", "rtc-version": "1.0.16", "timestamp": "2025-11-12T071137.667864+00:00"} {"message": "preloading plugins", "level": "INFO", "name": "livekit.agents", "packages": ["livekit.plugins.openai", "livekit.plugins.silero", "livekit.plugins.turn_detector", "av"], "timestamp": "2025-11-12T071137.668053+00:00"} {"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 88, "timestamp": "2025-11-12T071139.514838+00:00"} {"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 91, "timestamp": "2025-11-12T071139.532063+00:00"} {"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 97, "timestamp": "2025-11-12T071139.553221+00:00"} {"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 103, "timestamp": "2025-11-12T071139.576937+00:00"} {"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 88, "elapsed_time": 0.47, "timestamp": "2025-11-12T071139.981725+00:00"} {"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 91, "elapsed_time": 0.47, "timestamp": "2025-11-12T071140.001599+00:00"} {"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 97, "elapsed_time": 0.49, "timestamp": "2025-11-12T071140.039856+00:00"} {"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 103, "elapsed_time": 0.47, "timestamp": "2025-11-12T071140.049473+00:00"} {"message": "registered worker", "level": "INFO", "name": "livekit.agents", "id": "CAW_V6LMCsX7RVYj", "url": "https://air-76v7fg9o.livekit.cloud", "region": "US East B", "protocol": 16, "timestamp": "2025-11-12T071140.117218+00:00"} But after doing the agent dispatch as i showed earlier, a room is not visible in lk room list. And no logs come in the above logs and no phone call is received.
t
Hi there! Let's work through some possible reasons why your LiveKit agent might not be creating a room or receiving a phone call after a successful dispatch. I’m here to help you troubleshoot step-by-step: • Insufficient Workers: It’s important to make sure you have enough agent workers running and properly registered. You can use
lk agent status
to check if the workers are available. • Room Name Mismatch: Double-check that the room name in your dispatch request exactly matches the room name used in the
CreateSIPParticipant
API call. Even small differences can cause issues. • Dispatch Rules: Take a look at your dispatch rules to ensure they’re correctly set up to route calls to the right room and dispatch the agent. • SIP Trunk Configuration: Verify that your inbound and outbound SIP trunks are configured properly. Sometimes missing or misconfigured trunks can block calls from routing as expected. • Auto-Create Disabled: If auto-create is turned off, rooms won’t be created automatically during dispatch. It’s worth checking this setting in your configuration. • Authentication or Permissions: Make sure the API credentials you’re using for dispatch have the right admin permissions to create rooms and dispatch agents. For a deeper look, try checking your LiveKit server logs for any errors related to room creation or dispatch, and also confirm that the agent worker logs indicate it’s ready to accept jobs. If you’d like, I’m happy to guide you through any of these steps—just let me know! Sources: Agents telephony integration | LiveKit docs | pkg/service/agent_dispatch_service.go | Operational Best Practices | livekit/livekit_composite | DeepWiki
s
lk agent status Using project [air] Using agent [CA_oKWcdfYb5MxA] ┌─────────────────┬─────────────────┬─────────┬─────────┬────────────┬───────────┬───────────┬──────────────────────┐ │ ID │ Version │ Region │ Status │ CPU │ Mem │ Replicas │ Deployed At │ ├─────────────────┼─────────────────┼─────────┼─────────┼────────────┼───────────┼───────────┼──────────────────────┤ │ CA_oKWcdfYb5MxA │ v20251112070929 │ us-east │ Running │ 8m / 4000m │ 1.1 / 8GB │ 1 / 1 / 8 │ 2025-11-12T071105Z │ └─────────────────┴─────────────────┴─────────┴─────────┴────────────┴───────────┴───────────┴──────────────────────┘ await ctx.api.sip.create_sip_participant( api.CreateSIPParticipantRequest( _room_name_=ctx.room.name, _sip_trunk_id_=sip_outbound_trunk_id, _sip_call_to_=phone_number, _participant_identity_=participant_identity, _wait_until_answered_=True, ) ) Where do i check dispatch rules? How to check this "*Auto-Create Disabled*"? If auth was wrong then api call should have failed, right?
t
Let me guide you through how you can check and configure the dispatch rules and auto-create settings for your LiveKit agent: • Dispatch Rules: ◦ To see the existing SIP dispatch rules, you can use the
ListSIPDispatchRules
API or the equivalent SDK method. For instance, in Python:
rules = await sip_client.list_dispatch_rules()
◦ Dispatch rules help determine how incoming SIP calls are routed to rooms and whether agents are automatically dispatched. It’s important to make sure your rules are set up to fit your specific needs. • Auto-Creation of Rooms: ◦ Rooms will be automatically created during agent dispatch if the server’s
roomAllocator.AutoCreateEnabled
flag is set to true. ◦ This setting is part of your server configuration and isn’t accessible or changeable via API. If you’re self-hosting, you’ll want to check your configuration files or Helm charts for a setting like
ROOM_AUTOCREATE_ENABLED=true
. ◦ If you’re using LiveKit Cloud, auto-create is usually enabled by default. However, if dispatch is failing because rooms don’t exist, that might be a sign that auto-create is turned off. • Authentication: ◦ If your API call goes through successfully, that’s a good sign your authentication is set up correctly. Still, it’s worth double-checking that your API credentials have the right permissions to create rooms and dispatch agents. To dig a bit deeper, you can also list the current dispatches in a room using the
listDispatch
method in the SDK or CLI: • Here’s an example in Python:
dispatches = await lkapi.agent_dispatch.list_dispatch(room_name="my-room")
• And in the CLI:
lk dispatch list --room my-room
If you’d like, I’m here to help you verify your configuration or make sense of the results—just let me know! Sources: pkg/service/agent_dispatch_service.go | SIP dispatch rule | LiveKit docs | SIP Integration & Telephony | livekit/livekit_composite | DeepWiki | Agent dispatch | LiveKit Docs | Knowledge Base Content | livekit/livekit_composite | DeepWiki
s
twirp error not_found: requested room does not exist So room did not get created, tell me how to check for auto creation of room. I have cli and i have the console access
t
It looks like you're seeing the error
twirp error not_found: requested room does not exist
, which means the room wasn’t created during the dispatch process. I understand how this can be a bit confusing! The auto-creation of rooms is actually controlled by a server-side configuration flag (
roomAllocator.AutoCreateEnabled
), and unfortunately, it can’t be checked or changed directly through the CLI or API. Here’s a friendly guide to help you move forward: • For Self-Hosted Deployments: Take a look at your server configuration files or Helm charts for a setting like
ROOM_AUTOCREATE_ENABLED=true
. This setting controls whether rooms get created automatically during dispatch. • For LiveKit Cloud: Usually, auto-creation is turned on by default. If it’s not working as expected, reaching out to LiveKit support can help confirm your configuration. If you want to check if auto-creation is enabled in practice, here’s a simple way: • Try dispatching an agent to a room that doesn’t exist yet. If you get the "room not found" error, auto-creation is probably off. • If the dispatch works and the room gets created, then auto-creation is on. Please don’t hesitate to ask if you’d like a hand checking your server setup or understanding what you find—I’m here to help!
s
I want to only use outbound calls, do i still need dispatch rules?
t
I’m happy to help clarify this for you! Dispatch rules aren’t needed for outbound calls in LiveKit. They’re mainly used to manage how inbound SIP calls get routed to LiveKit rooms, like deciding based on trunk IDs or other details. For outbound calls, all you really need to do is set up your outbound SIP trunk and use the
CreateSIPParticipant
API to specify: • The destination number (
sip_call_to
). • The trunk you want to use (
sip_trunk_id
). • The room where you want to connect the participant (
room_name
). If you’d like, I’m here to help you step through setting up your outbound call configuration—just let me know! Sources: SIP Integration & Telephony | livekit/livekit_composite | DeepWiki | protobufs/livekit_sip.proto | Using Wavix to accept and make calls | LiveKit docs
s
what is wrong with this:
Copy code
claims = {
            "iss": self.api_key,
            "iat": now,
            "nbf": now,
            "exp": exp,
            "video": {
                "room": room_name,
                "roomJoin": True,
                "roomCreate": True,
            },
            "sip": {
                "call": True,
                "trunk": sip_trunk_id,   # <-- IMPORTANT
            }
        }
        room_config = {
            "agents": [
                {
                    "agentName": "agent_conversation_voice_kit",
                    "metadata": json_utils.dumps(room_metadata or {}),
                }
            ],
            "departureTimeout": 20,
        }
        claims["roomConfig"] = room_config

        token = jwt.encode(
            claims,
            self.api_secret,
            algorithm="HS256",
            headers={"typ": "JWT"}
        )

        log.info(f"Generated JWT token for SIP participant. Issuer: {self.api_key}")

        # Convert ws/wss → http/https
        http_url = self.livekit_url.replace("wss://", "https://").replace("ws://", "http://")

        # This is the SIP endpoint we want:
        url = f"{http_url}/twirp/livekit.SIP/CreateSIPParticipant"

        payload = {
            "sipTrunkId": sip_trunk_id,
            "sipCallTo": phone_number,
            "roomName": room_name,
            "participantIdentity": participant_identity,
            "participantName": participant_name,
            "krispEnabled": krisp_enabled,
            "waitUntilAnswered": wait_until_answered,
        }

        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        }

        log.info(f"Creating SIP participant in room '{room_name}' with trunk ID '{sip_trunk_id}'")
        log.debug(f"Request URL: {url}")
        log.debug(f"Request payload: {payload}")

        try:
            response = requests.post(url, json=payload, headers=headers, timeout=30)
            response.raise_for_status()
            log.info(f"Successfully created SIP participant in room '{room_name}'")
            return response.json()
Because the room is not getting created and no call is being made and no logs in the agent of the server and no errors on the api call
t
I understand how frustrating it can be when a room isn’t created, no call is made, and no logs appear even though the API call seems successful. Let’s walk through some possible reasons together: • SIP Trunk Provider Rejection: Sometimes the SIP trunk might silently reject the INVITE request. It’s a good idea to double-check that your trunk is properly configured and that the destination number is correct. • Call Status Not Progressing: If the call doesn’t reach a ringing or answered state, it might fail quietly. Keeping an eye on
sip.callStatus
through participant events can help you see how the call is progressing. • Timeouts: If you’re using
wait_until_answered
, make sure the call setup finishes within the timeout window (usually 30 seconds, or 80 seconds if using
WaitUntilAnswered
). • Misconfigured SIP Trunk: It’s important that the SIP trunk has the right credentials and routing. Sometimes authentication issues on the provider’s side can cause silent drops. • SIP Service Connectivity: The SIP service needs to be properly connected to Redis and the LiveKit server. Please check that the service is running smoothly and is accessible. Here are a few steps you can take to dig deeper: • Turn on participant event monitoring to watch for changes in
sip.callStatus
. • Double-check your SIP trunk configuration and credentials. • Review the logs on both the LiveKit server and SIP service to spot any errors or rejections. If you’d like, I’m here to help you through any of these steps—just let me know! Sources: Making outbound calls | LiveKit docs | pkg/service/sip.go | README.md | SIP APIs | LiveKit docs