Hey I have built a chatbot which gives response wh...
# ask-ai
a
Hey I have built a chatbot which gives response when we hit a certain endpoint(/api/screen), now i want to use livekit to add voice to my chatbot, can i use livekit for it
t
Thanks for reaching out, Ravinder. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Absolutely, LiveKit is a wonderful tool to add voice capabilities to your chatbot! It offers a range of features to help you build voice AI agents that can chat with users naturally through speech, combining speech-to-text (STT), large language models (LLM), and text-to-speech (TTS) seamlessly. Here are some key features you might find helpful: • Automatic turn-taking and real-time interruption handling, making conversations feel smooth and natural. • Support for multiple TTS providers with customizable voice options to suit your needs. • Integration with OpenAI Realtime API for quick, expressive voice interactions. • Frontend templates that make it easy to embed voice agents into your web and mobile apps. To get you started, I’d recommend checking out the Voice AI Quickstart. Also, the open-source playground is a great place to explore examples and tutorials. If you have any questions along the way, feel free to reach out—I’m here to help! Sources: LiveKit Docs | Text-to-speech (TTS) models | LiveKit Docs | examples/voice_agents/README.md | OpenAI and LiveKit partner to turn Advanced Voice into an API | Agent speech and audio | LiveKit Docs
a
my chatbot currently sends a response when we hit the (http:135....../api/screen) url
t
Thanks for reaching out! Could you please share a bit more about how you'd like to integrate LiveKit with your current chatbot? For instance, are you thinking of using LiveKit for voice input/output while your chatbot takes care of the logic and responses, or do you have a different kind of integration in mind? I'm here to help you figure this out!
a
yes looking for that only
t
I'm glad you're interested in integrating LiveKit for handling voice input and output while your chatbot manages the logic and responses! Here’s a friendly step-by-step guide to help you along: 1. Set up LiveKit: Start by installing the necessary dependencies like
livekit-agents
,
deepgram
, and
langchain
. Don’t forget to configure your API keys (LiveKit, Deepgram, etc.) in a
.env
file to keep everything running smoothly. 2. Use AgentSession: The
AgentSession
class is your go-to for managing voice interactions. It takes care of speech-to-text (STT), text-to-speech (TTS), and turn-taking, making your chatbot feel more natural. 3. Connect to your chatbot: You’ll want to adjust your chatbot so it sends responses to LiveKit’s TTS system. For example, when your chatbot generates a reply, you can pass it along to LiveKit to convert it into voice output. 4. Frontend integration: To make the experience seamless for users, use LiveKit’s frontend templates (React, Flutter, etc.) so they can chat with your bot using voice. For more detailed examples and handy code snippets, check out the Voice AI Quickstart. And please feel free to reach out if you’d like some help with any part of the setup—I’m here to support you every step of the way!
a
this is how i am trying to run it """ This script creates a LiveKit voice agent that uses a custom HTTP endpoint as its Large Language Model (LLM). How it works: 1. The agent listens to the user's speech using the Speech-to-Text (STT) engine. 2. It waits for the user to finish speaking (
is_end_of_speech
). 3. It sends the user's full transcribed message to a specified REST API endpoint. 4. It receives a text response from the API. 5. It uses the Text-to-Speech (TTS) engine to speak the API's response back to the user. """ import logging import aiohttp from collections.abc import AsyncIterable from dotenv import load_dotenv from livekit import agents from livekit.agents import Agent, AgentSession, JobContext, WorkerOptions from livekit.agents import llm as llm_module from livekit.plugins import cartesia, deepgram, silero from livekit.plugins.turn_detector.multilingual import MultilingualModel from livekit.agents.llm import LLM, ChatContext, ChatChunk # Load environment variables from a .env file load_dotenv() # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("custom-http-llm-agent") # --- Configuration --- # ❗️ IMPORTANT: Change this URL to your actual HTTP endpoint. CUSTOM_LLM_ENDPOINT_URL = "http://172.190.117.125:4000/api/screen" class CustomHTTPLLM(LLM): """ A custom LLM implementation that forwards requests to your HTTP endpoint. """ async def chat(self, _chat_ctx_: ChatContext) -> AsyncIterable[ChatChunk]: """ Implement the required chat method for the abstract LLM class. This method processes the chat context and yields ChatChunk objects. """ # Get the user's message from the chat context user_message = "" for msg in _chat_ctx_.messages: if msg.role == "user": user_message += msg.content if not user_message: return logger.info(f"Sending to custom LLM: '{user_message}'") # Call your custom HTTP endpoint _try_: async with aiohttp.ClientSession() as http_session: async with http_session.post( CUSTOM_LLM_ENDPOINT_URL, json={"message": user_message}, timeout=30 ) as resp: if resp.status == 200: data = await resp.json() response_text = data.get("response", "(API returned no response)") logger.info(f"Received from custom LLM: '{response_text}'") # Yield the response as a ChatChunk yield ChatChunk( text=response_text, role="assistant" ) _else_: error_text = await resp.text() logger.error(f"API Error - Status {resp.status}: {error_text}") yield ChatChunk( text=f"(API returned an error: {resp.status})", role="assistant" ) except Exception as e: logger.error(f"Failed to call custom LLM endpoint: {e}") yield ChatChunk( text="(Sorry, I couldn't connect to my brain.)", role="assistant" ) class CustomHTTPAgent(Agent): def __init__(self): super().__init__(instructions="You are a helpful AI girlfriend companion.") async def entrypoint(_ctx_: JobContext): """ This is the entrypoint for the agent worker. """ session = AgentSession( stt=deepgram.STT(model="nova-2", language="en"), tts=cartesia.TTS( model="sonic-2", # Replace with your own Cartesia voice ID voice="999aa6c5-29f7-47b5-ac37-50acfb18e443" ), vad=silero.VAD.load(), llm=CustomHTTPLLM(), # Use our custom HTTP LLM implementation _turn_detection_=MultilingualModel(), _preemptive_generation_=True, ) # Start the session with our custom agent await session.start(room=ctx.room, agent=CustomHTTPAgent()) # Optional: Greet the user when the agent joins the room await session.say("Hey babe, how are you doing today?") if name == "__main__": # This is the command-line interface for running the agent. # To run this script, use:
livekit-agent run custom-agent-script.py
agents.cli.run_app( WorkerOptions(_entrypoint_fnc_=entrypoint) )
t
Your script is nicely set up for integrating LiveKit with your chatbot through a custom HTTP endpoint. It thoughtfully manages the speech-to-text (STT) process, sends the transcribed message to your API, and then uses text-to-speech (TTS) to respond back to the user. Here are a few friendly tips to help everything run smoothly: • Make sure the
CUSTOM_LLM_ENDPOINT_URL
is accessible and properly configured to handle POST requests with the expected JSON payload. • Try testing the
CustomHTTPLLM
class on its own to confirm it can successfully send and receive data from your API. • Double-check the TTS voice ID (
voice="999aa6c5-29f7-47b5-ac37-50acfb18e443"
) to ensure it matches a valid Cartesia voice model in your account. • Use the
livekit-agent run
command to start the agent and keep an eye on the logs for any errors or connectivity hiccups. If you run into any specific challenges or want a hand with anything else, please don’t hesitate to reach out—I’m here to help!
a
response = { "success": True, "message": result.get("message", ""), "flow_type": session_data.get("flow_type", "initial"), "current_step": session_data.get("current_step", 0), "session_id": session_id, _# Use the session_id that was set earlier_ "detailed_result": detailed_result } return. jsonify(response), this is how my api/screen endpoint return the response
t
Your API response structure looks clear and well-defined. To make sure everything works smoothly with your LiveKit integration, you might want to tweak the
CustomHTTPLLM
class a bit to pull out the important fields from your response. Specifically, adjusting the
chat
method to handle the
message
field from your API’s JSON response would be a great step. Here’s a friendly example of how you could do that:
Copy code
async def chat(self, chat_ctx: ChatContext) -> AsyncIterable[ChatChunk]:
    user_message = ""
    for msg in chat_ctx.messages:
        if msg.role == "user":
            user_message += msg.content

    if not user_message:
        return

    try:
        async with aiohttp.ClientSession() as http_session:
            async with http_session.post(
                CUSTOM_LLM_ENDPOINT_URL,
                json={"message": user_message},
                timeout=30
            ) as resp:
                if resp.status == 200:
                    data = await resp.json()
                    response_text = data.get("message", "(API returned no message)")
                    yield ChatChunk(
                        text=response_text,
                        role="assistant"
                    )
                else:
                    error_text = await resp.text()
                    yield ChatChunk(
                        text=f"(API Error: {resp.status})",
                        role="assistant"
                    )
    except Exception as e:
        yield ChatChunk(
            text="(Sorry, I couldn't connect to my brain.)",
            role="assistant"
        )
This way, the
message
field from your API response is used as the assistant’s reply. If you have any questions or want to explore this further, just let me know—I’m here to help!
a
DEBUGlivekittokio_tungstenite:tlsencryptionrustls103tokio tungstenitetlsencryption:rustls - Added 140/140 native root certificates (ignored 0) DEBUGlivekitrustls:clienths73rustlsclient:hs - No cached session for DnsName("ai-girlfriend-ytp58eo8.livekit.cloud") DEBUGlivekitrustls:clienths132rustlsclient:hs - Not resuming any session DEBUGlivekitrustls:clienths615rustlsclient:hs - Using ciphersuite TLS13_AES_128_GCM_SHA256 DEBUGlivekitrustls:clienttls13142rustlsclient:tls13 - Not resuming DEBUGlivekitrustls:clienttls13381rustlsclient:tls13 - TLS1.3 encrypted extensions: [] DEBUGlivekitrustls:clienths472rustlsclient:hs - ALPN protocol is None DEBUGlivekittungstenite:🤝client95tungstenite🤝:client - Client handshake done. DEBUGlivekit.agentsusing audio io:
RoomIO
->
AgentSession
->
TranscriptSynchronizer
->
RoomIO
DEBUGlivekit.agentsusing transcript io:
AgentSession
->
TranscriptSynchronizer
->
RoomIO
DEBUGlivekit.agentspre-connect audio received DEBUGlivekit.agentspre-connect audio buffer pushed DEBUGlivekit.agentsstart reading stream ERRORlivekit.agentsError in _llm_inference_task Traceback (most recent call last): File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/appuser/.local/lib/python3.11/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/generation.py", line 125, in _llm_inference_task async for chunk in llm_node: File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/agent.py", line 399, in llm_node async with activity_llm.chat( ^^^^^^^^^^^^^^^^^^ TypeError: CustomHTTPLLM.chat() got an unexpected keyword argument 'tools' ERRORlivekit.agentsError in _llm_inference_task Traceback (most recent call last): File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/appuser/.local/lib/python3.11/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/generation.py", line 125, in _llm_inference_task async for chunk in llm_node: File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/agent.py", line 399, in llm_node async with activity_llm.chat( ^^^^^^^^^^^^^^^^^^ TypeError: CustomHTTPLLM.chat() got an unexpected keyword argument 'tools' {"message": "Error in _llm_inference_task\nTraceback (most recent call last):\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs\n return await fn(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/appuser/.local/lib/python3.11/site-packages/opentelemetry/util/_decorator.py\", line 71, in async_wrapper\n return await func(*args, **kwargs) # type: ignore\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/generation.py\", line 125, in _llm_inference_task\n async for chunk in llm_node:\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/agent.py\", line 399, in llm_node\n async with activity_llm.chat(\n ^^^^^^^^^^^^^^^^^^\nTypeError: CustomHTTPLLM.chat() got an unexpected keyword argument 'tools'", "level": "ERROR", "name": "livekit.agents", "pid": 40, "job_id": "AJ_g9zdtSH8xbhZ", "timestamp": "2025-10-13T124552.963508+00:00"}
t
It looks like the error is happening because the
CustomHTTPLLM.chat()
method is receiving an unexpected keyword argument
'tools'
. This usually means that the
chat
method in your
CustomHTTPLLM
class isn’t currently set up to accept this argument, but LiveKit’s framework is sending it along during execution. Here’s a friendly tip to help you fix this: 1. Try updating the
chat
method in your
CustomHTTPLLM
class to accept
**kwargs
. This way, it can gracefully handle any extra keyword arguments without running into errors. For example:
Copy code
async def chat(self, chat_ctx: ChatContext, **kwargs) -> AsyncIterable[ChatChunk]:
    # Your existing implementation
Making this change will ensure that any additional arguments the framework passes are simply ignored unless you specifically want to use them. Please feel free to reach out if you run into any other issues or if you’d like me to walk you through the next steps—I’m here to help!
a
DEBUGlivekit.agentsresumed false interrupted speech ERRORlivekit.agentsError in _llm_inference_task Traceback (most recent call last): File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/appuser/.local/lib/python3.11/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/generation.py", line 125, in _llm_inference_task async for chunk in llm_node: File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/agent.py", line 399, in llm_node async with activity_llm.chat( TypeError: 'async_generator' object does not support the asynchronous context manager protocol ERRORlivekit.agentsError in _llm_inference_task Traceback (most recent call last): File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/appuser/.local/lib/python3.11/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/generation.py", line 125, in _llm_inference_task async for chunk in llm_node: File "/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/agent.py", line 399, in llm_node async with activity_llm.chat( TypeError: 'async_generator' object does not support the asynchronous context manager protocol {"message": "Error in _llm_inference_task\nTraceback (most recent call last):\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs\n return await fn(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/appuser/.local/lib/python3.11/site-packages/opentelemetry/util/_decorator.py\", line 71, in async_wrapper\n return await func(*args, **kwargs) # type: ignore\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/generation.py\", line 125, in _llm_inference_task\n async for chunk in llm_node:\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/agent.py\", line 399, in llm_node\n async with activity_llm.chat(\nTypeError: 'async_generator' object does not support the asynchronous context manager protocol", "level": "ERROR", "name": "livekit.agents", "pid": 41, "job_id": "AJ_3eRsJdHtCVcA", "timestamp": "2025-10-13T124912.341150+00:00"}
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!