can you please let me know is there any built-in f...
# ask-ai
c
can you please let me know is there any built-in function for hang_up and call_transfer ?
t
Thanks for reaching out, Uzair. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks for reaching out! I wanted to let you know that LiveKit doesn’t have direct built-in functions named
hang_up
or
call_transfer
, but don’t worry—these features are definitely supported through LiveKit's APIs: • Hang Up: You can use the
delete_room
API to gracefully end the call for everyone involved. • Call Transfer: The
transfer_sip_participant
API lets you transfer the caller to another number or SIP endpoint smoothly. These APIs give you the flexibility to implement these features exactly how you need. If you'd like, I’m more than happy to share more details or examples to help you get started—just let me know! Sources: Call forwarding | LiveKit docs | LiveKit Docs | Agents telephony integration | LiveKit docs | agent.py | Agent speech and audio | LiveKit docs
c
i wan to use it in Pre lead qualification outreach
t
To help you use
hang_up
and
call_transfer
during your pre-lead qualification outreach, you can seamlessly integrate LiveKit's APIs into your workflow: • Hang Up: You can use the
delete_room
API to gracefully end the call for all participants. This comes in handy when the lead interaction is finished or if you need to wrap things up. • Call Transfer: The
transfer_sip_participant
API allows you to transfer the lead to another number or SIP endpoint, like a human agent or a specific department, making the process smooth and efficient. These APIs can be triggered automatically based on how the lead responds or other conditions you set. If you'd like, I’m here to provide implementation examples or help you set up this workflow step-by-step. Just let me know! Sources: Agents telephony integration | LiveKit docs | agent.py | Company directory phone assistant | LiveKit Docs | sip-refer/README.mdoc | Agent-assisted warm transfer | LiveKit docs
c
I’m running a LiveKit agent using a custom
SalesAgent
. During conversations, the logs only show user transcripts — for example:
Copy code
2025-11-12 11:41:25,353 - DEBUG livekit.agents - received user transcript {"user_transcript": "..."}
I want to also capture and log the bot (agent) responses in the same console/log file, so I can see both sides of the conversation. How can I modify my LiveKit agent setup to log both user and bot messages in real time?
t
To help you log both user and bot messages in real time for your
SalesAgent
, here’s a friendly approach you can try out: • Use the
conversation_item_added
Event:
This handy event captures all conversation messages as they happen. Here’s an example to get you started:
Copy code
@session.on("conversation_item_added")
def conversation_item_added(item):
    participant_type = "User" if item.item.role == "user" else "Bot"
    print(f"[{item.item.created_at}] {participant_type}: {item.item.text}")
• Log to External Services: You can also forward these logs to services like Datadog or CloudWatch for easier monitoring in one place. • Ensure Complete Capture: Don’t forget to use
RoomInputOptions.close_on_disconnect
to make sure all logs are saved when a disconnection happens. If you’d like, I’m here to walk you through any part of this or provide more details—just let me know! Sources: docs/index.yaml | Logs, metrics, and telemetry | LiveKit docs | Log collection | LiveKit docs | Knowledge Base Content | livekit/livekit_composite | DeepWiki | How to capture real-time agent transcriptions during conversations
c
2025-11-12 142848,505 - DEBUG asyncio - Using selector: EpollSelector 2025-11-12 142848,510 - INFO livekit.agents - starting worker {"version": "1.2.18", "rtc-version": "1.0.18"} 2025-11-12 142848,515 - INFO livekit.agents - preloading plugins {"packages": ["livekit.plugins.openai", "livekit.plugins.silero", "livekit.plugins.deepgram", "av"]} 2025-11-12 142848,538 - DEBUG asyncio - Using selector: EpollSelector 2025-11-12 142848,540 - INFO livekit.agents - initializing job runner {"tid": 68986} 2025-11-12 142848,549 - INFO livekit.agents - job runner initialized {"tid": 68986, "elapsed_time": 0.0} 📄 Loaded context: 1405 characters 2025-11-12 142849,754 - DEBUG livekit.agents - input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"]} 2025-11-12 142849,755 - DEBUG livekit.agents - http_session(): creating a new httpclient ctx 2025-11-12 142849,770 - DEBUG livekit.agents - using audio io:
RoomIO
->
AgentSession
->
TranscriptSynchronizer
->
RoomIO
2025-11-12 142849,771 - DEBUG livekit.agents - using transcript io:
AgentSession
->
TranscriptSynchronizer
->
RoomIO
2025-11-12 142849,780 - ERROR livekit - failed to emit event conversation_item_added Traceback (most recent call last): File "/usr/local/lib/python3.12/dist-packages/livekit/rtc/event_emitter.py", line 58, in emit callback(*callback_args) File "/tmp/ipython-input-1916331812.py", line 19, in on_conversation_item text = item.item.text ^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/dist-packages/pydantic/main.py", line 991, in getattr raise AttributeError(f'{type(self).name!r} object has no attribute {item!r}') AttributeError: 'ChatMessage' object has no attribute 'text' 2025-11-12 142859,192 - INFO livekit.agents - shutting down worker {"id": "unregistered"} 2025-11-12 142859,195 - DEBUG livekit.agents - shutting down job task {"reason": "", "user_initiated": false} 2025-11-12 142859,197 - DEBUG livekit.agents - job exiting {"reason": "", "tid": 68986, "job_id": "simulated-job-0887620f7cfa"} 2025-11-12 142859,245 - ERROR livekit - failed to emit event conversation_item_added Traceback (most recent call last): File "/usr/local/lib/python3.12/dist-packages/livekit/rtc/event_emitter.py", line 58, in emit callback(*callback_args) File "/tmp/ipython-input-1916331812.py", line 19, in on_conversation_item text = item.item.text ^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/dist-packages/pydantic/main.py", line 991, in getattr raise AttributeError(f'{type(self).name!r} object has no attribute {item!r}') AttributeError: 'ChatMessage' object has no attribute 'text' 2025-11-12 142859,249 - DEBUG livekit.agents - input stream detached {"participant": "user", "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"]} 2025-11-12 142901,255 - DEBUG livekit.agents - session closed {"reason": "job_shutdown", "error": null} 2025-11-12 142901,257 - DEBUG livekit.agents - http_session(): closing the httpclient ctx import logging import asyncio from livekit.agents import JobContext, WorkerOptions, AgentSession, jupyter from your_agent_file import SalesAgent # adjust to your file logger = logging.getLogger("livekit.agents") logging.basicConfig( level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s", ) async def entrypoint(ctx: JobContext): await ctx.connect() agent = SalesAgent() session = AgentSession() # Log both user and bot messages def on_conversation_item(message): role = getattr(message, "role", "unknown").upper() text = getattr(message, "content", None) or getattr(message, "text", None) if text: logger.debug(f"{role}: {text}") session.on("conversation_item_added", on_conversation_item) # Start the session and keep it alive await session.start(room=ctx.room, agent=agent) while True: await asyncio.sleep(1)
t
It looks like the error is happening because the
ChatMessage
object doesn’t have a
text
attribute. Instead, you’ll want to use the
text_content
property to get the message text. Here’s an updated version of your
on_conversation_item
function that should do the trick:
Copy code
def on_conversation_item(item):
    role = getattr(item, "role", "unknown").upper()
    text = getattr(item, "text_content", None)  # Use text_content instead of text
    if text:
        logger.debug(f"{role}: {text}")
This change should help you log both user and bot messages properly. If you have any more questions or need a hand with anything else, just let me know—I’m here to help! Sources: basics/label_messages.py | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/util...
c
2025-11-13 111212,868 - DEBUG asyncio - Using selector: EpollSelector 2025-11-13 111212,870 - INFO livekit.agents - starting worker {"version": "1.2.18", "rtc-version": "1.0.19"} 2025-11-13 111212,871 - INFO livekit.agents - preloading plugins {"packages": ["livekit.plugins.openai", "livekit.plugins.silero", "livekit.plugins.deepgram", "av"]} 2025-11-13 111212,874 - DEBUG asyncio - Using selector: EpollSelector 2025-11-13 111212,874 - INFO livekit.agents - initializing job runner {"tid": 15874} 2025-11-13 111212,876 - INFO livekit.agents - job runner initialized {"tid": 15874, "elapsed_time": 0.0} 🔗 Connecting to LiveKit room... 🤖 Initializing agent... 📄 Loaded script: 1809 characters 2025-11-13 111213,180 - ERROR livekit.agents - unhandled exception while running the job task Traceback (most recent call last): File "/usr/lib/python3.12/asyncio/tasks.py", line 314, in __step_run_and_handle_result result = coro.send(None) ^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/dist-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/dist-packages/livekit/agents/ipc/job_proc_lazy_main.py", line 240, in _traceable_entrypoint await self._job_entrypoint_fnc(job_ctx) File "/tmp/ipython-input-311825287.py", line 56, in entrypoint agent = DynamicSalesAgent() ^^^^^^^^^^^^^^^^^^^ File "/tmp/ipython-input-311825287.py", line 39, in init tts = cartesia.TTS() ^^^^^^^^^^^^ AttributeError: module 'cartesia' has no attribute 'TTS' # 🤖 Run this in a NEW Colab cell to start your bot from livekit.agents import Agent, JobContext, AgentSession, WorkerOptions, jupyter from livekit.plugins import openai, deepgram, silero from pathlib import Path def load_context(): """Load script from context directory""" context_dir = Path("/content/context") all_content = "" for file_path in context_dir.glob("*"): if file_path.is_file() and file_path.name != "instructions.txt": try: content = file_path.read_text(encoding='utf-8') all_content += f"\n=== {file_path.name} ===\n{content}\n" except: pass return all_content.strip() class DynamicSalesAgent(Agent): def __init__(self): # Load script context = load_context() print(f"📄 Loaded script: {len(context)} characters") # Load instructions instructions_file = Path("/content/context/instructions.txt") if instructions_file.exists(): instructions = instructions_file.read_text(encoding='utf-8') else: instructions = "You are a helpful sales agent." # Replace placeholder with actual script final_instructions = instructions.replace("{SCRIPT_CONTENT}", context) # Setup voice components llm = openai.LLM.with_cerebras(model="llama-3.3-70b") stt = deepgram.STT() tts = cartesia.TTS() vad = silero.VAD.load() super().__init__( instructions=final_instructions, stt=stt, llm=llm, tts=tts, vad=vad ) async def on_enter(self): print("🎙️ Bot started - greeting caller...") self.session.generate_reply(user_input="Greet the caller warmly in one sentence.") async def entrypoint(ctx: JobContext): print("🔗 Connecting to LiveKit room...") await ctx.connect() print("🤖 Initializing agent...") agent = DynamicSalesAgent() print("🎬 Starting session...") session = AgentSession() await session.start(room=ctx.room, agent=agent) print("✅ Starting LiveKit bot...") jupyter.run_app( WorkerOptions(entrypoint_fnc=entrypoint), jupyter_url="https://jupyter-api-livekit.vercel.app/api/join-token" ) I want to use CartesiaTTS:
t
It looks like the error is happening because the Cartesia TTS plugin isn’t being used quite right. No worries, I’m here to help you get it sorted out! To fix this, you can follow these steps: 1. First, make sure the Cartesia plugin is installed by running:
Copy code
uv add "livekit-agents[cartesia]~=1.2"
1. Next, import the TTS plugin correctly like this:
Copy code
from livekit.plugins import cartesia

tts = cartesia.TTS(
    model="sonic-3",
    voice="f786b574-daa5-4673-aa0c-cbe3e8534c02",
)
1. Finally, don’t forget to set your Cartesia API key in the environment variable
CARTESIA_API_KEY
. If you run into any more questions or need a hand with any of these steps, just let me know—I’m happy to help! Sources: Cartesia TTS plugin guide | LiveKit Docs | livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/__init__.py
c
I really want bot conversation ❗ LIVEKIT DOES NOT EMIT BOT/LLM/TTS EVENTS IN JUPYTER MODE This is official LiveKit behavior. Inside the Jupyter runner: on_llm_response() is NOT called session.on("tts") NEVER fires session.on("message") NEVER fires Bot responses are NOT streamed back to Python Only user STT is forwarded (your logs confirm it)
t
Thanks for reaching out! I wanted to share that LiveKit doesn’t emit bot/LLM/TTS events in Jupyter mode because the playground UI uses older transcription events and doesn’t support showing agent responses when audio track publishing is turned off. Instead, bot responses are sent through the
lk.transcription
text stream topic. If you'd like to capture these bot responses, you’ll want to set up a custom receiver that listens to the
lk.transcription
text stream. You can also keep an eye on agent session events like
conversation_item_added
to stay updated on the conversation flow. If you’d like, I’m here to help you with implementing the text stream receiver or anything else you might need—just let me know! Sources: How to Set Up Speech-to-Text Input with Text-Only Output in LiveKit Agents | Agents v0.x migration guide - Python | LiveKit docs | Agents v0.x migration guide - Node.js | LiveKit Docs | Events and error handling | LiveKit docs | livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti...
c
Hi, I need some guidance. I’m building an outreach bot using LiveKit, and I already have all the core functionality working in my FastAPI backend and database. Right now, I’m testing everything with Streamlit, but the problem is that I have to run it from the terminal or a Jupyter cell to interact with the bot. That’s fine for testing, but not suitable for a real outreach/lead-qualification platform. For the production version, I need a frontend where: • Users can upload scripts and instructions • Users can upload phone numbers • Users can specify transfer numbers or destinations • Users can start outreach campaigns • Users can view dashboards and campaign results • For each phone number called, I can store
q
/
nq
variables and the full conversation (bot + user + transcript) Given this, which frontend framework should I use?
t
When it comes to building a production outreach bot platform, LiveKit warmly recommends using Next.js with React. This framework is a wonderful fit for your needs because: • It supports server-side rendering (SSR) and static site generation (SSG), which really helps with performance and SEO. • It works beautifully with LiveKit's React components (
@livekit/components-react
), making integration smooth. • It offers API routes for backend tasks, like generating tokens, which can simplify your workflow. • There are official LiveKit templates and examples, such as the "Next.js Voice Agent Starter," that are built using Next.js to help you get started quickly. You can easily scaffold a production-ready frontend using the LiveKit CLI with this command:
Copy code
lk app create --template voice-assistant-frontend
If you’d like, I’m here to help guide you through the setup or answer any questions you have along the way! Sources: Client SDKs | livekit/livekit_composite | DeepWiki | README.md | Web and mobile frontends | LiveKit docs | complex-agents/nova-sonic/README.md
c
yes tell me how can i achieve this in live kit i already achieved dynamic scrpts fin stream lit but the main issue is can you give me a path in live kit how can i achive these as well • LiveKit voice agent that: ◦ Calls users ◦ Runs your qualification logic ◦ Can hangup ◦ Can transfer when qualified • Streamlit UI (basic) ◦ User enters script → converted into context + instructions dynamically • API + DB ◦ Campaign records ◦ Phone numbers ◦ Qualification results • A strong agent instruction template (great!) So your foundation is already 70% ready for MVP. ✅ 2) Minimal UI – EXACT Features for MVP Your first version must stay small, but complete enough for real use. Here’s the absolutely minimal UI features you MUST include: ✔️ A) Campaign Setup Fields: • Campaign Name • Upload Contacts (CSV) ◦
name
◦
phone
◦
timezone
(optional) • Upload/Enter Script Content • Agents Transfer Numbers (multiple) • Campaign Time Window: ◦ Start Time ◦ End Time ◦ Days Allowed (Mon–Sun toggles) ⚡ Optional simple UI controls: • Voice Agent: choose voice (DG/Kokoro) • Max attempts per number ✔️ B) Campaign Control Panel User should be able to: • Start Campaign • Pause Campaign • Resume Campaign • Stop Campaign • View the current calling number • See next numbers queued • See live status: ◦ "Ringing" ◦ "Talking" ◦ "Qualified – transferring" ◦ "Not Qualified – ending" ◦ "No Answer" ◦ "Busy – Rescheduling" ✔️ C) Results Dashboard (very minimal) A simple report table: Caller NameNumberResultNotesCall TimeJohn Doe+1234QualifiedTransferred2025-11-14Smith+7890Not QualifiedFailed age criteria………………
Filters: • Filter by Campaign • Filter by Result ◦ Qualified ◦ Not Qualified ◦ Busy / Reschedule ◦ No Answer ◦ In Progress 👉 This is enough for MVP. ✅ 3) Minimal BACKEND requirements (FastAPI) Your MVP backend should include: ✔️ A) Contact Upload API • Save all contacts to DB with campaign_id ✔️ B) Campaign Engine A single FastAPI background worker: • Picks next number • Tells LiveKit agent to dial • Waits for agent result callback • Updates DB accordingly • Moves to next number ✔️ C) Qualification Results Callback LiveKit / Agent → FastAPI webhook: •
call_id
•
qualification_status
•
transfer_number
•
notes
✔️ D) Transfer Logic When agent → “qualified” FastAPI should: • Pick the correct transfer number (round robin or priority order) • Pass it to agent via function tool: ◦
transfer_call(number)
✔️ E) Scheduler (Optional in MVP but recommended) Allows user to set: • Run campaign from 10am to 6pm • Avoid calling at night This can be done with: • APScheduler • Or cron-like triggers in FastAPI
t
To build a LiveKit voice agent for outreach campaigns, here’s a simple guide to get you started: 1. Start with the Outbound Caller Template: Begin by using the
outbound-caller-python
template to initiate calls and manage room creation. You can set it up easily by running this command:
Copy code
lk app create --template outbound-caller-python my-outreach-agent
1. Implement Campaign Setup: Customize the template to load your contact lists (like CSV files) and schedule batch calls. Adding dynamic prompts will help personalize each outreach. 2. Build a Control Panel: Consider using the
agent-starter-react
template to create a dashboard where you can set up campaigns, monitor them live, and make manual adjustments whenever needed. 3. Design Agent Workflows: Plan out your outreach flow in phases—greeting, delivering messages, collecting responses, and transferring calls—to keep things smooth and effective. 4. Log Results: Make sure to capture important events like
conversation_item_added
, and save transcripts, call outcomes, and related data in a database for easy review. 5. Deploy at Scale: When you’re ready to go big, use Docker to containerize your agent and deploy it on platforms like AWS or Render. Setting up autoscaling will help manage large campaigns effortlessly. If you’d like, I’m here to help with any specific part—whether it’s campaign scheduling, CRM integration, or anything else. Just let me know! Sources: External data and RAG | LiveKit Docs | README.md | TEMPLATE.md | Workflows | LiveKit docs | Logs, metrics, and telemetry | LiveKit Docs
c
yes tell me how can i achieve this in live kit i already achieved dynamic scrpts fin stream lit but the main issue is can you give me a path in live kit how can i achive these as well and what are the recommendation to do that • LiveKit voice agent that: ◦ Calls users ◦ Runs your qualification logic ◦ Can hangup ◦ Can transfer when qualified • Streamlit UI (basic) ◦ User enters script → converted into context + instructions dynamically • API + DB ◦ Campaign records ◦ Phone numbers ◦ Qualification results • A strong agent instruction template (great!) So your foundation is already 70% ready for MVP. ✅ 2) Minimal UI – EXACT Features for MVP Your first version must stay small, but complete enough for real use. Here’s the absolutely minimal UI features you MUST include: ✔️ A) Campaign Setup Fields: • Campaign Name • Upload Contacts (CSV) ◦
name
◦
phone
◦
timezone
(optional) • Upload/Enter Script Content • Agents Transfer Numbers (multiple) • Campaign Time Window: ◦ Start Time ◦ End Time ◦ Days Allowed (Mon–Sun toggles) ⚡ Optional simple UI controls: • Voice Agent: choose voice (DG/Kokoro) • Max attempts per number ✔️ B) Campaign Control Panel User should be able to: • Start Campaign • Pause Campaign • Resume Campaign • Stop Campaign • View the current calling number • See next numbers queued • See live status: ◦ "Ringing" ◦ "Talking" ◦ "Qualified – transferring" ◦ "Not Qualified – ending" ◦ "No Answer" ◦ "Busy – Rescheduling" ✔️ C) Results Dashboard (very minimal) A simple report table: Caller NameNumberResultNotesCall TimeJohn Doe+1234QualifiedTransferred2025-11-14Smith+7890Not QualifiedFailed age criteria……………… Filters: • Filter by Campaign • Filter by Result ◦ Qualified ◦ Not Qualified ◦ Busy / Reschedule ◦ No Answer ◦ In Progress 👉 This is enough for MVP. ✅ 3) Minimal BACKEND requirements (FastAPI) Your MVP backend should include: ✔️ A) Contact Upload API • Save all contacts to DB with campaign_id ✔️ B) Campaign Engine A single FastAPI background worker: • Picks next number • Tells LiveKit agent to dial • Waits for agent result callback • Updates DB accordingly • Moves to next number ✔️ C) Qualification Results Callback LiveKit / Agent → FastAPI webhook: •
call_id
•
qualification_status
•
transfer_number
•
notes
✔️ D) Transfer Logic When agent → “qualified” FastAPI should: • Pick the correct transfer number (round robin or priority order) • Pass it to agent via function tool: ◦
transfer_call(number)
✔️ E) Scheduler (Optional in MVP but recommended) Allows user to set: • Run campaign from 10am to 6pm • Avoid calling at night This can be done with: • APScheduler • Or cron-like triggers in FastAPI
t
To help you achieve your goals for a LiveKit-based outreach platform, here’s a friendly step-by-step path you can follow: 1. LiveKit Voice Agent: ◦ Start with the
outbound-caller-python
template to manage calls, hangups, and transfers. You can extend it to include your qualification logic and connect it with FastAPI for smooth backend communication. ◦ Consider implementing
transfer_call
as a handy function tool to handle qualified leads and dynamically pass transfer numbers. 1. Streamlit UI: ◦ Create a simple interface where users can upload scripts that are then converted into agent instructions on the fly. Streamlit’s file upload and form components make this super straightforward. 1. API + DB: ◦ Build a FastAPI backend with endpoints for uploading contacts, managing campaigns, and handling result callbacks. A relational database like PostgreSQL will be great for storing campaign records, phone numbers, and qualification results. 1. Minimal UI Features: ◦ For setting up campaigns, include fields like campaign name, contact uploads (CSV), script content, transfer numbers, and time windows. ◦ In the control panel, give users the ability to start, pause, resume, and stop campaigns, plus view live call statuses. ◦ For the results dashboard, add filters by campaign and result, and display a simple report table for easy insights. 1. Backend Recommendations: ◦ Use FastAPI’s background tasks to run a campaign engine that picks numbers, dials via LiveKit, and updates the database based on agent callbacks. ◦ Set up a webhook to receive qualification results from LiveKit and keep your campaign status up to date. ◦ Implement transfer logic with a round-robin or priority-based approach to select transfer numbers smoothly. ◦ Optionally, use APScheduler or cron-like triggers to schedule campaigns within specific time windows. If you’d like, I’d be happy to provide detailed implementation examples for any part you’re interested in, like the FastAPI backend or LiveKit agent integration. Just let me know!
c
got it just tell me i already use stream lit on my bot setting but wehen i run stream lit i have to came back and re run the cell to run live kit bot ? i don't able to start from stream lit ? # 🤖 Run this in a NEW Colab cell to start your bot from livekit.agents import Agent, JobContext, AgentSession, WorkerOptions, jupyter from livekit.plugins import openai, deepgram, silero from pathlib import Path def load_context(): """Load script from context directory""" context_dir = Path("/content/context") all_content = "" for file_path in context_dir.glob("*"): if file_path.is_file() and file_path.name != "instructions.txt": try: content = file_path.read_text(encoding='utf-8') all_content += f"\n=== {file_path.name} ===\n{content}\n" except: pass return all_content.strip() class DynamicSalesAgent(Agent): def __init__(self): # Load script context = load_context() print(f"📄 Loaded script: {len(context)} characters") # Load instructions instructions_file = Path("/content/context/instructions.txt") if instructions_file.exists(): instructions = instructions_file.read_text(encoding='utf-8') else: instructions = "You are a helpful sales agent." # Replace placeholder with actual script final_instructions = instructions.replace("{SCRIPT_CONTENT}", context) # Setup voice components llm = openai.LLM.with_cerebras(model="llama-3.3-70b") stt = deepgram.STT() tts = deepgram.TTS() vad = silero.VAD.load() super().__init__( instructions=final_instructions, stt=stt, llm=llm, tts=tts, vad=vad ) async def on_enter(self): print("🎙️ Bot started - greeting caller...") self.session.generate_reply(user_input="Greet the caller warmly in one sentence.") async def entrypoint(ctx: JobContext): print("🔗 Connecting to LiveKit room...") await ctx.connect() print("🤖 Initializing agent...") agent = DynamicSalesAgent() print("🎬 Starting session...") session = AgentSession() await session.start(room=ctx.room, agent=agent) print("✅ Starting LiveKit bot...") jupyter.run_app( WorkerOptions(entrypoint_fnc=entrypoint), jupyter_url="https://jupyter-api-livekit.vercel.app/api/join-token" )
t
To help you start your LiveKit bot directly from a Streamlit app without having to rerun Jupyter cells, here are a couple of friendly approaches you can try: 1. Subprocess Approach (Recommended): This method runs the LiveKit bot as a separate process from Streamlit, which helps avoid any event loop conflicts. Here’s a simple example:
Copy code
import subprocess
import sys

if st.button("Start LiveKit Bot"):
    process = subprocess.Popen([sys.executable, "agent.py", "start"])
    st.write("Bot started with PID:", process.pid)

if st.button("Stop LiveKit Bot"):
    process.terminate()
    st.write("Bot stopped")
1. Thread-Based Approach: You can also run the bot in a separate thread with its own asyncio event loop. This lets you integrate more closely with Streamlit, but it does mean you’ll need to manage the event loop carefully. Both of these methods will let your bot run independently from Streamlit’s synchronous execution, giving you more flexibility. If you’d like, I’m happy to walk you through more detailed examples for either approach—just let me know! Sources: README.md | livekit-agents/livekit/agents/cli/_run.py | App templates | LiveKit docs
c
but i want to start bot in stream lit not separately
t
To get you started with running the LiveKit bot right inside Streamlit, a great way is to use a thread-based approach. This lets the bot run in its own thread with a dedicated asyncio event loop, so your Streamlit app stays smooth and responsive. Here’s a friendly example to guide you:
Copy code
import streamlit as st
import asyncio
import threading
from livekit.agents import JobContext, WorkerOptions, AgentSession

class BotRunner:
    def __init__(self):
        self.thread = None
        self.loop = None

    def start_bot(self):
        if self.thread and self.thread.is_alive():
            st.warning("Bot is already running!")
            return

        self.thread = threading.Thread(target=self._run_bot)
        self.thread.daemon = True
        self.thread.start()
        st.success("Bot started successfully!")

    def _run_bot(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

        async def entrypoint(ctx: JobContext):
            await ctx.connect()
            session = AgentSession()
            await session.start(room=ctx.room, agent=DynamicSalesAgent())

        opts = WorkerOptions(entrypoint_fnc=entrypoint)
        self.loop.run_until_complete(opts.run())

# Streamlit UI
st.title("LiveKit Bot Controller")

if "bot_runner" not in st.session_state:
    st.session_state.bot_runner = BotRunner()

if st.button("Start Bot"):
    st.session_state.bot_runner.start_bot()
This way, your bot fits right into Streamlit and handles the asyncio event loop smoothly in its own thread. If you have any questions or want me to walk you through any part, just let me know—I’m here to help!
c
not able to implement in streamlit app can you please tell me in detail what i need to do that
t
Let's get you started with running the LiveKit bot directly inside your Streamlit app! Just follow these friendly steps, and if you hit any bumps along the way, I’m here to help you out. 1. Install Required Dependencies: First, make sure you have all the necessary libraries installed. You can do this easily with:
Copy code
pip install streamlit livekit-agents asyncio
1. Set Up the Bot Logic: Next, let's create a Python class that will manage your bot. This class will take care of starting the bot in its own thread with an asyncio event loop, keeping things running smoothly:
Copy code
import asyncio
import threading
from livekit.agents import JobContext, WorkerOptions, AgentSession

class BotRunner:
    def __init__(self):
        self.thread = None
        self.loop = None

    def start_bot(self):
        if self.thread and self.thread.is_alive():
            return "Bot is already running!"

        self.thread = threading.Thread(target=self._run_bot)
        self.thread.daemon = True
        self.thread.start()
        return "Bot started successfully!"

    def _run_bot(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

        async def entrypoint(ctx: JobContext):
            await ctx.connect()
            session = AgentSession()
            await session.start(room=ctx.room, agent=DynamicSalesAgent())

        opts = WorkerOptions(entrypoint_fnc=entrypoint)
        self.loop.run_until_complete(opts.run())
1. Integrate with Streamlit: Now, let's build a simple Streamlit interface so you can easily start and stop your bot with just a click:
Copy code
import streamlit as st

st.title("LiveKit Bot Controller")

if "bot_runner" not in st.session_state:
    st.session_state.bot_runner = BotRunner()

if st.button("Start Bot"):
    message = st.session_state.bot_runner.start_bot()
    st.write(message)
1. Run the Streamlit App: Save your code to a file, maybe name it
app.py
, and then run it with this command:
Copy code
streamlit run app.py
1. Test the Bot: Finally, just click the "Start Bot" button in your Streamlit app, and your LiveKit bot will launch right from there! This setup is designed to keep your bot running smoothly and asynchronously, so it won’t interrupt your Streamlit app’s interface. If you have any questions or want me to walk you through any part, just let me know—I’m happy to help!
c
File "D:\CWIT\VoiceBot-Real-Time-Voice-Tanslation\venv\Lib\site-packages\aiohttp\connector.py", line 1581, in _create_direct_connection raise last_exc File "D:\CWIT\VoiceBot-Real-Time-Voice-Tanslation\venv\Lib\site-packages\aiohttp\connector.py", line 1550, in _create_direct_connection transp, proto = await self._wrap_create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<7 lines>... ) ^ File "D:\CWIT\VoiceBot-Real-Time-Voice-Tanslation\venv\Lib\site-packages\aiohttp\connector.py", line 1291, in _wrap_create_connection raise client_error(req.connection_key, exc) from exc aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host localhost:7880 ssl:default [Multiple exceptions: [Errno 10061] Connect call failed ('::1', 7880, 0, 0), [Errno 10061] Connect call failed ('127.0.0.1', 7880)]
t
It looks like the error is telling us that the LiveKit server at
localhost:7880
isn’t reachable right now. No worries, I’m here to help you get this sorted out! Here’s a friendly step-by-step guide: 1. Make Sure the LiveKit Server is Up and Running: You can start the server locally by running this command:
Copy code
livekit-server --dev
If you’re using Docker, try this:
Copy code
docker run -p 7880:7880 -p 7881:7881 livekit/livekit-server --dev
1. Double Check the WebSocket URL: Make sure the URL looks like
ws://localhost:7880
for a regular WebSocket, or
wss://localhost:7880
if you’re using a secure connection. 2. Look Into Docker Networking: If Docker is involved, sometimes
localhost
needs to be swapped out for
host.docker.internal
on Mac or Windows, or
172.17.0.1
on Linux. 3. Try Testing the Connection: You can use the LiveKit CLI to see if the connection works like this:
Copy code
lk room join --url ws://localhost:7880 --api-key devkey --api-secret secret my_first_room
1. Give the Connection Another Shot: Make sure your agent is set up to retry connecting enough times, like so:
Copy code
from livekit.agents import WorkerOptions
opts = WorkerOptions(ws_url="ws://localhost:7880", max_retry=30)
If you hit any bumps or want me to walk you through any of these steps, just let me know—I’m here to help! Sources: Diagnosing Connection Errors with Connection Test Utility | livekit-plugins/livekit-plugins-rtzr/livekit/plugins/rtzr/stt.py | Ports and firewall | LiveKit docs | Samples~/Basic/Assets/RoomManager.cs | Self-hosting the Ingress Service | LiveKit docs
c
message, payload = await protocol.read() # type: ignore[union-attr] ^^^^^^^^^^^^^^^^^^^^^ File "D:\CWIT\VoiceBot-Real-Time-Voice-Tanslation\venv\Lib\site-packages\aiohttp\streams.py", line 680, in read await self._waiter aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected WARNINGlivekit.agentsfailed to connect to livekit, retrying in 4s Traceback (most recent call last): File "D:\CWIT\VoiceBot-Real-Time-Voice-Tanslation\venv\Lib\site-packages\livekit\agents\worker.py", line 695, in _connection_task ws = await self._http_session.ws_connect( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<6 lines>... ) ^ File "D:\CWIT\VoiceBot-Real-Time-Voice-Tanslation\venv\Lib\site-packages\aiohttp\client.py", line 1076, in _ws_connect resp = await self.request( ^^^^^^^^^^^^^^^^^^^ ...<11 lines>... ) ^ File "D:\CWIT\VoiceBot-Real-Time-Voice-Tanslation\venv\Lib\site-packages\aiohttp\client.py", line 779, in _request resp = await handler(req) ^^^^^^^^^^^^^^^^^^ File "D:\CWIT\VoiceBot-Real-Time-Voice-Tanslation\venv\Lib\site-packages\aiohttp\client.py", line 757, in _connect_and_send_request await resp.start(conn) File "D:\CWIT\VoiceBot-Real-Time-Voice-Tanslation\venv\Lib\site-packages\aiohttp\client_reqrep.py", line 539, in start message, payload = await protocol.read() # type: ignore[union-attr] ^^^^^^^^^^^^^^^^^^^^^ File "D:\CWIT\VoiceBot-Real-Time-Voice-Tanslation\venv\Lib\site-packages\aiohttp\streams.py", line 680, in read await self._waiter aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected
t
The
ServerDisconnectedError
happens when the WebSocket connection to the LiveKit server unexpectedly ends. Don’t worry, I’m here to help you through it! Here are some steps you can follow to get things back on track: 1. Make Sure the LiveKit Server is Running: First, check that the server is up and reachable at
localhost:7880
. If it’s not running, you can start it with this command:
Copy code
livekit-server --dev
1. Use Retry Logic: Sometimes connections hiccup, so it’s helpful to try reconnecting with exponential backoff. Here’s a simple way to do that:
Copy code
retry_delay = min(retry_count * 2, 10)
await asyncio.sleep(retry_delay)
1. Set Heartbeat Intervals: To keep the connection healthy and spot any issues early, set up a heartbeat like this:
Copy code
ws = await session.ws_connect(url, heartbeat=30.0)
1. Handle WebSocket Errors Gracefully: Wrapping your connection code in try-except blocks helps manage errors such as
WSMsgType.ERROR
or timeouts smoothly:
Copy code
try:
    msg = await asyncio.wait_for(ws.receive(), timeout=5)
except asyncio.TimeoutError:
    # Handle timeout
1. Clean Up Connections Properly: When you’re done with a room, always call
Room.disconnect()
to prevent abrupt disconnections. If you’d like, I’m here to help you implement any of these steps or answer any questions you have. Just let me know! Sources: Connecting to LiveKit | LiveKit docs | livekit-plugins/livekit-plugins-deepgram/livekit/plugins/deepgram/stt_v2.py
c
hey what wi do i sue this LIVEKIT_CONFIG = { 'url': 'wss://streamlit-i8', # Your LiveKit Cloud URL 'api_key': '', # Your API Key from LiveKit Cloud 'api_secret': 'ulpp # Your API Secret from LiveKit Cloud } with my correct api key in stream lit and get dynamic script and instruction prompt from my ui than run my bot in live kit play ground it's just me not my working bot can you please tell me where i am wrong ?
t
Let's walk through how to set up LiveKit in Streamlit and dynamically generate scripts for your bot together. Here’s a simple guide to get you started: 1. Set Up LiveKit Configuration: First, make sure your LiveKit credentials are correctly set up like this:
Copy code
LIVEKIT_CONFIG = {
    'url': 'wss://your-livekit-url',
    'api_key': 'your-api-key',
    'api_secret': 'your-api-secret'
}
1. Generate Tokens Dynamically: Next, use the LiveKit Python SDK to create tokens for room access. Here’s a handy function for that:
Copy code
from livekit import api

def generate_token(room_name, participant_identity):
    token = api.AccessToken(
        LIVEKIT_CONFIG['api_key'], 
        LIVEKIT_CONFIG['api_secret']
    ).with_identity(participant_identity) \
     .with_grants(api.VideoGrants(room_join=True, room=room_name))
    return token.to_jwt()
1. Integrate with Streamlit: Now, let’s create a Streamlit form that takes user inputs to generate scripts dynamically:
Copy code
import streamlit as st

st.title("LiveKit Bot Configuration")
room_name = st.text_input("Room Name")
participant_identity = st.text_input("Participant Identity")

if st.button("Generate Token"):
    token = generate_token(room_name, participant_identity)
    st.write("Generated Token:", token)
1. Run the Bot: Finally, you can use Python’s
subprocess
module to start the bot based on the inputs from Streamlit like this:
Copy code
import subprocess

if st.button("Start Bot"):
    process = subprocess.Popen([
        'python', 'your_agent_script.py', 'start'
    ])
    st.write("Bot started with PID:", process.pid)
If you have any questions or need help with any specific part, just let me know—I’m here to help! Sources: Voice AI quickstart | LiveKit docs | Deploying to custom environments | LiveKit Docs | Generating tokens | LiveKit docs | complex-agents/shopify-voice-shopper/shopify-voice-frontend/.env.example | client/app/(chat)/page.tsx
c
means we have to use livekit meet not live kit agent playground ? is livekit meet free?
t
I'm glad you're exploring LiveKit! LiveKit Meet is a wonderful, free, open-source video conferencing app designed to help people connect in real time. You can easily try it out at meet.livekit.io, or if you're feeling adventurous, customize it using the source code. On the other hand, the LiveKit Agent Playground is a special space made just for testing and prototyping AI agents built with the LiveKit Agents Framework. It’s more about experimenting with how agents behave rather than focusing on the user interface. So, if you’re aiming to test AI agents, the Agent Playground is definitely the way to go. But if you want to have real-time video chats or bring people together, LiveKit Meet is your best bet. Please feel free to ask if you’d like me to explain anything further—I’m here to help! Sources: Agents playground | LiveKit Docs | Meet KITT | LiveKit | Use Case: Video Conferencing | LiveKit | README.md | README.md
c
def generate_token(_room_name_, _participant_identity_, _participant_name_="User"): """Generate LiveKit access token for room access""" try: token = (api.AccessToken(LIVEKIT_CONFIG['api_key'], LIVEKIT_CONFIG['api_secret']) .with_identity(_participant_identity_) .with_name(_participant_name_) .with_grants(api.VideoGrants( _room_join_=True, room=_room_name_, )) .with_ttl(hours=2) # 2 hour expiration ).to_jwt() return token except Exception as e: st.error(f"❌ Token generation failed: {e}") return None Token generation failed: AccessToken.with_ttl() got an unexpected keyword argument 'hours'
t
It looks like the error is happening because the
with_ttl()
method in the LiveKit Python SDK expects a
datetime.timedelta
object, rather than keyword arguments like
hours
. No worries though! Here's a simple way to fix this:
Copy code
import datetime
from livekit.api import AccessToken, VideoGrants

def generate_token(room_name, participant_identity, participant_name="User"):
    try:
        token = (
            AccessToken(api_key=LIVEKIT_CONFIG['api_key'], api_secret=LIVEKIT_CONFIG['api_secret'])
            .with_identity(participant_identity)
            .with_name(participant_name)
            .with_grants(VideoGrants(room_join=True, room=room_name))
            .with_ttl(datetime.timedelta(hours=2))  # Set TTL to 2 hours
            .to_jwt()
        )
        return token
    except Exception as e:
        st.error(f"❌  Token generation failed: {e}")
        return None
This way, the TTL will be set properly. If you have any more questions or need a hand with anything else, just let me know—I'm here to help! Sources: livekit-api/livekit/api/access_token.py | livekit-agents/livekit/agents/inference/_utils.py | packages/livekit-server-sdk/src/ServiceBase.ts | src/main/kotlin/io/livekit/server/ServiceClientBase.kt
c
hey it's resoolved and Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiVXNlciIsInZpZGVvIjp7InJvb21Kb2luIjp0cnVlLCJyb29tIjoidm9pY2UtdGVzdC1yb29tIiwiY2FuUHVibGlzaCI6dHJ1ZSwiY2FuU3Vic2NyaWJlIjp0cnVlLCJjYW5QdWJsaXNoRGF0YSI6dHJ1ZX0sInN1YiI6InRlc3RlciIsImlzcyI6InlvdXJfYXBpX0FQSXpEd2syc3IyckZyNWtleV9oZXJlIiwibmJmIjoxNzYzMjAxODkyLCJleHAiOjE3NjMyMDkwOTJ9.cRathvbaYnDaWk7htRfRcSyJmFKCu5qPWiQDyXvxIUw Room: voice-test-room but when i enter in room there only me no bot communication and status is disconnectedd
t
I'm sorry to hear that your bot is showing a disconnected status and not communicating in the room. There could be a few reasons for this, so let's walk through them together: 1. Bot Initialization Timeout: Please check if the bot is properly initialized and connected to the room. It’s important to ensure the bot's session starts correctly and that it has the necessary permissions to publish and subscribe to tracks. 2. Duplicate Identity: Sometimes, if another participant is using the same identity, it can cause the bot to disconnect. Double-check to make sure identities are unique. 3. Network Issues: Make sure your network allows connections to the LiveKit server and that the WebSocket URL is set up correctly. 4. Room Permissions: Verify that the token you’re using grants the bot permission to join the room and publish tracks. 5. Server-Side Disconnection: It’s also worth checking if the room was closed or if the bot was removed via the LiveKit API. To get to the bottom of this, try monitoring the bot's logs for any disconnection reasons or errors during initialization. If you’d like, I’m here to help you troubleshoot specific logs or configurations—just let me know! Sources: Diagnosing Connection Errors with Connection Test Utility | Connecting to LiveKit | LiveKit docs | Sources/LiveKit/Protos/livekit_models.pb.swift | JavaScript/TypeScript SDK | livekit/livekit_composite | DeepWiki
c
whrere i see logs?
t
I'm here to help you view the logs for your LiveKit bot and server. Here are some friendly steps you can follow: 1. LiveKit Server Logs: If you're running the LiveKit server locally or using Docker, you can check the terminal or container logs where the server is running. For Docker, simply use:
Copy code
docker logs [container_id]
1. Bot Logs: When you run the bot script, the logs will show up in the terminal where the script is running. Just make sure logging is enabled in your bot script like this:
Copy code
import logging
logging.basicConfig(level=logging.DEBUG)
1. Streamlit Logs: If you're running the bot through Streamlit, take a look at the terminal where you started the Streamlit app. The bot’s logs should appear there if everything is set up correctly. 2. LiveKit Cloud Logs: For those using LiveKit Cloud, you might find logs in the LiveKit Cloud dashboard, usually under the monitoring or analytics section. Please don’t hesitate to reach out if you’d like a hand accessing or understanding these logs—I’m happy to guide you through it!
c
is there necassary when i am using stream lit app to make docker as well to run bot?
t
I totally understand your question! You don’t have to use Docker to run your bot with a Streamlit app. You can absolutely run the bot directly from your local environment, as long as all the necessary dependencies are installed and everything is set up correctly. That said, Docker does offer some great benefits: • Consistency: It makes sure your bot runs the same way on any system. • Isolation: It helps prevent any conflicts with other apps or dependencies on your computer. • Ease of Deployment: It makes moving your bot to production or the cloud much smoother. If you’re still developing and working locally, Docker is totally optional. But when you’re ready for production or collaborating with a team, Docker can be a real game-changer. If you'd like, I’m here to help you get Docker set up for your bot—just let me know!
c
it's 2nd day and i am not able to do this
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
c
if i using outbound- python starter to test my bot is i need to configure sip trunck?
HEY tomorrow it's working fine but today it gave an error
Copy code
UnboundLocalError                         Traceback (most recent call last)
/tmp/ipython-input-1999222343.py in <cell line: 0>()
     62 
     63 print("✅ Starting LiveKit bot...")
---> 64 jupyter.run_app(
     65     WorkerOptions(entrypoint_fnc=entrypoint),
     66     jupyter_url="https://jupyter-api-livekit.vercel.app/api/join-token"

/usr/local/lib/python3.12/dist-packages/livekit/agents/jupyter.py in run_app(server, jupyter_url)
    129 
    130     args = proto.CliArgs(
--> 131         log_level="DEBUG", devmode=True, url=ws_url, api_key=api_key, api_secret=api_secret
    132     )
    133     cli._run_worker(server, args, jupyter=True)
UnboundLocalError: cannot access local variable 'api_key' where it is not associated with a value
is it doable in livekit i can capture incomming voice packet and give to another service befor giving to stt of deapgram