How to deploy agent code on LiveKit Cloud ? My tok...
# ask-ai
f
How to deploy agent code on LiveKit Cloud ? My token server is deployed on render
t
Thanks for reaching out, venu. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to deploy your agent code on LiveKit Cloud while keeping your token server hosted on Render, here’s a simple step-by-step guide to help you out: 1. First, install the LiveKit CLI (make sure it’s version 2.5 or later):
npm install -g livekit-cli
2. Next, authenticate with LiveKit Cloud:
lk cloud auth
This will open a browser so you can link your LiveKit Cloud project easily. 3. Then, go to your agent project folder and deploy:
Copy code
cd your-agent-project
lk agent create
This command takes care of creating a Dockerfile if you don’t have one, packages and uploads your agent code, and deploys it on LiveKit Cloud. 4. When you want to update your agent, just run:
lk agent deploy
This will do a smooth rolling update without any downtime. Just so you know, your token server on Render can stay exactly as it is—it handles issuing access tokens to clients, which is a different job. The agent on LiveKit Cloud just needs the connection credentials to your LiveKit instance and doesn’t interact directly with the token server. If you hit any snags or have questions, feel free to reach out—I’m here to help! Sources: Deploying to LiveKit Cloud | LiveKit Docs | Deploying to production | LiveKit Docs
f
When I run lk agent create is my agent live on cloud ?
t
Yep, running
lk agent create
gets your agent up and running on LiveKit Cloud. This command takes care of registering the agent, uploading the code, building the image, and deploying it to your project, so it’s all set to handle requests. If you have any more questions or need a hand with anything, just let me know—I’m here to help! Sources: Deploying to production | LiveKit Docs | Deploying to LiveKit Cloud | LiveKit Docs
f
How to get the entire audio session transcript
t
Hey there! If you want to grab the entire audio session transcript in LiveKit, here are some easy ways to do it: • Access the Complete Session History: You can simply use the
session.history
property to get the full conversation history anytime you need it. • Save Transcript After Session Ends: A handy trick is to add a shutdown callback that automatically saves the transcript when the session wraps up. Here's an example:
Copy code
from datetime import datetime
import json

def entrypoint(ctx: JobContext):
    async def write_transcript():
        current_date = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"/tmp/transcript_{ctx.room.name}_{current_date}.json"
        with open(filename, 'w') as f:
            json.dump(session.history.to_dict(), f, indent=2)
        print(f"Transcript for {ctx.room.name} saved to {filename}")

    ctx.add_shutdown_callback(write_transcript)
• Real-time Transcript Access: You can also listen for events like
conversation_item_added
or
user_input_transcribed
to grab transcripts as they happen. • STT Streams: For real-time transcript processing, using Speech-to-Text streams works great:
Copy code
async for ev in stt_stream:
    if ev.type == stt.SpeechEventType.FINAL_TRANSCRIPT:
        transcript_text = ev.alternatives[0].text
If you have any questions or want me to walk you through this, just let me know—I’m here to help! Sources: Text and transcriptions | LiveKit Docs | main.py | Session recording and transcripts | LiveKit Docs
f
I want the session transcript after the end of session
t
Hey there! To save the session transcript automatically once the session ends, you can use the
add_shutdown_callback
method. Here’s a little example to get you started:
Copy code
from datetime import datetime
import json

def entrypoint(ctx: JobContext):
    async def write_transcript():
        current_date = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"/tmp/transcript_{ctx.room.name}_{current_date}.json"
        with open(filename, 'w') as f:
            json.dump(session.history.to_dict(), f, indent=2)
        print(f"Transcript for {ctx.room.name} saved to {filename}")

    ctx.add_shutdown_callback(write_transcript)
This little snippet will save your transcript as a JSON file right when the session wraps up. Feel free to tweak the file path or format to fit your needs. If you’d like a hand setting this up, just give me a shout!
f
I want to write the session history into a database at the end of the session
t
To save the session history into your database at the end of the session, you can tweak the shutdown callback to insert the transcript. Here’s a friendly example to get you started:
Copy code
from datetime import datetime
import json
import your_database_library  # Swap this out for the database library you’re actually using

def entrypoint(ctx: JobContext):
    async def write_transcript_to_db():
        # Turn the session history into a dictionary
        transcript_data = session.history.to_dict()

        # Example: Insert into your database (just replace with your own DB logic)
        db_connection = your_database_library.connect("your_connection_string")
        cursor = db_connection.cursor()

        # Example query (feel free to adjust the table/fields)
        query = "INSERT INTO session_transcripts (room_name, transcript, created_at) VALUES (%s, %s, %s)"
        values = (ctx.room.name, json.dumps(transcript_data), datetime.now())

        cursor.execute(query, values)
        db_connection.commit()
        cursor.close()
        db_connection.close()

        print(f"Transcript for {ctx.room.name} saved to the database")

    ctx.add_shutdown_callback(write_transcript_to_db)
Just swap out
your_database_library
and tweak the connection and query details to fit your setup. This way, your session transcript will be safely stored in your database as soon as the session wraps up. If you want a hand with anything else, just let me know—I’m here to help!
f
I have hosted my agent on LiveKit Cloud and token server on render and my user is joining the room but the agent is not joining
t
Hey there! To get to the bottom of why your agent isn’t joining the room, could you share a bit more info with me? • Have you double-checked that your
LIVEKIT_URL
,
LIVEKIT_API_KEY
, and
LIVEKIT_API_SECRET
are all set up correctly on LiveKit Cloud? • Is your token server on Render creating valid tokens that include the right
roomJoin
permissions? • Are you seeing any error messages or logs from the agent when it tries to connect? • How are you handling room creation? Are rooms already created before the agent tries to join, or is the agent supposed to join automatically? • Do your logs show that the worker has successfully registered with LiveKit Cloud? Once I have these details, I’ll be able to help you figure this out and get things running smoothly. Sources: LiveKit Docs | README.md | Authentication Examples | livekit/livekit_composite | DeepWiki | Web and mobile frontends | LiveKit Docs
f
in my agents framework I am using Cartesia for TTS. How do I change the voice
t
Hey there! If you want to change the voice in the Cartesia TTS framework for your agent, here are some easy ways to do it: • Set Voice During Initialization:
Copy code
from livekit.plugins import cartesia

tts = cartesia.TTS(
    model="sonic-2",
    voice="voice-id-here"  # Just swap this with the voice ID you want
)
• Update Voice Dynamically:
Copy code
# Switch to a different voice ID anytime
tts.update_options(voice="new-voice-id")
• Override Voice in Agent Constructor:
Copy code
from livekit.agents import Agent
from livekit.plugins import cartesia

class AssistantManager(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant.",
            tts=cartesia.TTS(voice="voice-id-here")
        )
• Fetch Available Voices: You can grab a list of all available voices using the Cartesia API like this:
Copy code
import requests

headers = {
    "X-API-Key": os.getenv("CARTESIA_API_KEY"),
    "Cartesia-Version": "2024-08-01",
    "Content-Type": "application/json",
}
response = requests.get("<CARTESIA_API_URL>/voices", headers=headers)
if response.status_code == 200:
    available_voices = response.json()
Just swap out
<CARTESIA_API_URL>
with the actual base URL for the Cartesia API. If you hit any bumps or want me to walk you through it, just give me a shout! Sources: Workflows | LiveKit Docs | agent/main.py | Cartesia TTS integration guide | LiveKit Docs | livekit-plugins/livekit-plugins-cartesia/livekit/plugins/cartesia/tts.py
f
in a room where agent and user is there, from server side who is the local participant and remote participant
t
When you're in a LiveKit room with an agent and a user, the terms "local participant" and "remote participant" depend on who's looking at it: • From the agent's point of view: The agent is the
local participant
, and the user is the
remote participant
. • From the user's point of view: The user is the
local participant
, and the agent is the
remote participant
. • From the server's point of view: Both are just participants. The agent has a
kind
value of
AGENT
, and the user has a
kind
value of
STANDARD
. The server doesn’t really label anyone as "local" or "remote." If anything’s unclear or you want to dive deeper, just let me know—I’m here to help! Sources: Inside a session | LiveKit Docs | Rooms, participants, and tracks | LiveKit Docs
f
how to get the remote participant data in server side
t
Hey there! If you want to grab remote participant data on the server side in LiveKit, here are some easy ways to do it: • Using RoomServiceClient: This is a handy way to list all participants or get info about a specific participant in a room.
Copy code
// Node.js example
const roomClient = new RoomServiceClient(host, apiKey, secret);

// List participants in a room
const participants = await roomClient.listParticipants(roomName);

// Get specific participant details
const participantInfo = await roomClient.getParticipant(roomName, identity);
• Within a Connected Room Session: If you’re already inside a connected room (like with LiveKit Agents), you can loop through remote participants like this:
Copy code
# Python example
for rp in room.remote_participants.values():
    print(rp.identity)
• Real-Time Updates: You can also listen for events such as participants joining or leaving to keep track of them as things happen. Usually, participant data includes things like identity, name, metadata, attributes, connection quality, speaking status, and track publications. If you want me to walk you through any part or share more examples tailored to what you’re working on, just let me know—I’m here to help! Sources: Inside a session | LiveKit Docs | room.go | livekit/src/room/mod.rs | Managing participants | LiveKit Docs | packages/livekit-server-sdk/src/RoomServiceClient.ts
f
what is PARTICIPANT_KIND_AGENT
t
PARTICIPANT_KIND_AGENT
is a value in LiveKit's
ParticipantKind
enum that helps identify a participant as an AI agent or bot. It’s a handy way to tell apart agents created with the LiveKit Agents framework from regular users in a session. Here’s a quick rundown: • Purpose: Marks AI agents and bots in a LiveKit room. • Value: Numeric value is
4
. • Usage: Helps sort participants into types like
STANDARD
(end-users),
INGRESS
(stream ingestion),
EGRESS
(stream consumption),
SIP
(telephony users), and
AGENT
(AI agents). • Agent-Specific Features: Some SDKs offer extra properties for agents, like
isAgent
to check if a participant is an agent, and
agentState
to keep track of the agent’s status. This setup makes it easier for apps to handle different participant types with the right logic or permissions. If you want me to explain anything further, just let me know—I’m here to help! Sources: packages/livekit-rtc/src/proto/participant_pb.ts | Rooms, participants, and tracks | LiveKit Docs | Room & Participant Management | livekit/livekit_composite | DeepWiki | livekit-rtc/livekit/rtc/_proto/participant_pb2.py | livekit/src/room/participant/mod.rs
f
async def start_session(_ctx_: agents.JobContext): logger.info(_f_"Starting session for context: {ctx}") default_voice = "Sophie" selected_voice_id: Optional[str] = None for participant in ctx.room.remote_participants.values(): if participant.kind != rtc.ParticipantKind.PARTICIPANT_KIND_AGENT: selected_voice_id = participant.attributes.get("voice") break if not selected_voice_id or selected_voice_id not in VOICE_MAP: logger.info(_f_"No selected voice found. Taking up default voice") selected_voice_id=default_voice voice_id = VOICE_MAP[selected_voice_id] agent_instance = Evi() @_ctx_.room.on('participant_attributes_changed') def on_participant_muted(_changed_attributes_: dict[str, str],_participant_: rtc.Participant): if participant.kind != rtc.ParticipantKind.PARTICIPANT_KIND_STANDARD: return if "paused" in _changed_attributes_: state = participant.attributes.get("paused") if state == True: agent_instance.puased = True logger.info(_f_"Agent is Paused ************ ") pass session= AgentSession( stt=deepgram.STT(model="nova-3", language="multi"), llm=groq.LLM(model="meta-llama/llama-4-scout-17b-16e-instruct"), tts=cartesia.TTS(model="sonic-2", voice=voice_id["id"], language= voice_id["language"]), vad=ctx.proc.userdata["vad"], _turn_detection_=MultilingualModel() ) await session.start( room=ctx.room, agent=agent_instance, _room_input_options_=RoomInputOptions( audio_enabled=True, video_enabled=False, noise_cancellation= None, ) ) async def run_agent(_metadata_:dict={}): ctx=agents.JobContext(metadata=json.dumps(metadata)) await start_session(ctx) if name == "__main__": agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=start_session,prewarm_fnc=prewarm)) can you validate this code and see if everthing is fine