agreeable-queen-43452
10/13/2025, 12:34 PMtall-airline-16756
10/13/2025, 12:34 PMtall-airline-16756
10/13/2025, 12:34 PMagreeable-queen-43452
10/13/2025, 12:36 PMtall-airline-16756
10/13/2025, 12:36 PMagreeable-queen-43452
10/13/2025, 12:36 PMtall-airline-16756
10/13/2025, 12:37 PMlivekit-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!agreeable-queen-43452
10/13/2025, 12:40 PMis_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)
)tall-airline-16756
10/13/2025, 12:40 PMCUSTOM_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!agreeable-queen-43452
10/13/2025, 12:42 PMtall-airline-16756
10/13/2025, 12:43 PMCustomHTTPLLM 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:
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!agreeable-queen-43452
10/13/2025, 12:46 PMRoomIO -> 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"}tall-airline-16756
10/13/2025, 12:46 PMCustomHTTPLLM.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:
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!agreeable-queen-43452
10/13/2025, 12:49 PMtall-airline-16756
10/13/2025, 12:50 PM