import asyncio import logging from livekit.agents ...
# ask-ai
b
import asyncio import logging from livekit.agents import ( AgentSession, JobContext, JobProcess, WorkerOptions, cli, metrics, AgentFalseInterruptionEvent, RoomInputOptions, UserStateChangedEvent, MetricsCollectedEvent, ) from livekit.plugins import openai, silero, noise_cancellation from src.api.routes import run_fastapi from src.utils.config import ( LLM_MODEL_NAME, LOG_LEVEL, STT_MODEL_NAME, VoiceConfig, LoadBalancingConfig, ) from src.utils.logger import setup_logging from src.voice_assistant import Assistant from dotenv import load_dotenv from src.utils.tts_provider import create_tts load_dotenv() disconnect_task = None def prewarm(proc: JobProcess) -> None: proc.userdata["vad"] = silero.VAD.load( min_speech_duration=VoiceConfig.min_speech_duration, min_silence_duration=VoiceConfig.min_silence_duration, activation_threshold=VoiceConfig.activation_threshold, force_cpu=VoiceConfig.force_cpu, padding_duration=VoiceConfig.padding_duration, max_buffered_speech=VoiceConfig.max_buffered_speech, ) async def entrypoint(ctx: JobContext) -> None: logger = logging.getLogger("support-assistant") logger.info("Initializing support assistant...") await ctx.connect() tts_instance = create_tts() session = AgentSession( llm=openai.LLM(model=LLM_MODEL_NAME), stt=openai.STT(language=VoiceConfig.language, model=STT_MODEL_NAME), tts=tts_instance, vad=ctx.proc.userdata["vad"], preemptive_generation=True, user_away_timeout=5, ) @session.on("user_state_changed") def _on_user_state_changed(ev: UserStateChangedEvent): global disconnect_task if ev.new_state == "away": logger.info("User inactive 30s → asking if they are still there...") session.generate_reply(instructions="ask user if they are still there") # Start a background disconnect timer async def delayed_disconnect(): await asyncio.sleep(15) # wait another 15s # Check if still away if session.user_state == "away": logger.info("No response after warning → disconnecting") try: await ctx.delete_room() except Exception as e: logger.warning( f"Room deletion raised (likely already closed): {e}" ) disconnect_task = asyncio.create_task(delayed_disconnect()) elif ev.new_state == "active": logger.info("User became active again, cancelling pending disconnect") if disconnect_task and not disconnect_task.done(): disconnect_task.cancel() disconnect_task = None @session.on("agent_false_interruption") def _on_false_interrupt(ev: AgentFalseInterruptionEvent): logger.info("False positive interruption detected, resuming...") session.generate_reply(instructions=ev.extra_instructions or "") usage_collector = metrics.UsageCollector() @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) usage_collector.collect(ev.metrics) async def log_usage(): summary = usage_collector.get_summary() logger.info(f"Usage summary: {summary}") ctx.add_shutdown_callback(log_usage) await session.start( agent=Assistant(), room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ), ) try: await session.say( "Hi there! I'm Maya, your voice assistant specialized in personalized skincare consultations. " "Are you looking for skincare products, or a gift for someone?", allow_interruptions=False, ) logger.info("Initial greeting delivered to user") except Exception as e: logger.error(f"Failed to deliver greeting: {e}") if name == "__main__": setup_logging() run_fastapi() worker_opts = WorkerOptions( entrypoint_fnc=entrypoint, load_threshold=LoadBalancingConfig.load_threshold, num_idle_processes=LoadBalancingConfig.num_idle_processes, max_retry=LoadBalancingConfig.max_retry, shutdown_process_timeout=LoadBalancingConfig.shutdown_timeout, initialize_process_timeout=LoadBalancingConfig.initialize_timeout, prewarm_fnc=prewarm, ) cli.run_app(worker_opts) Can i create voice+chat bot and for chat i want to expose a fastapi endpoint which will get the user message as payload and will return the answer in following structure class ChatRequest(BaseModel): message: str chatId: Optional[str] = None class ChatResponse(BaseModel): chatId: str response: str products: Optional[List[Dict]] = None options: Optional[List[str]] = None conversationHistory: Optional[List[Dict]] = None createdAt: str step: Optional[str] = None
t
Thanks for reaching out, Mayank. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You can totally create a voice and chat bot using LiveKit and set up a FastAPI endpoint for chat functionality. Here’s a friendly overview of how to get this going: 1. Voice Bot with LiveKit: - Use the VoicePipelineAgent or MultimodalAgent to handle voice interactions. - Set up components like Speech-to-Text (STT), Large Language Model (LLM), and Text-to-Speech (TTS). - Keep the conversation flowing smoothly with ChatContext to track chat history. 2. FastAPI Endpoint for Chat: - Build a FastAPI app with a /chat POST endpoint. - Use the same LLM as your voice bot to process what users say. - Send back responses in the format you want, including optional extras like products and options. 3. Synchronizing Voice and Chat: - Share the ChatContext between your voice bot and FastAPI endpoint so the conversation feels seamless. - For bigger setups, consider using shared memory or an external store like Redis. 4. Deployment: - Run the LiveKit agent worker to handle voice chats. - Host your FastAPI app to manage chat messages. If you’d like, I’m here to help with detailed steps or any part of this setup you want to dive into! Just let me know. Sources: agent.py | livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | agent-examples/agent_examples/pipeline_agent.py | server/requirements.txt | agent/main.py
b
sure
t
Here’s a friendly and clear plan to help you create a voice and chat bot using LiveKit, along with a FastAPI endpoint for chat functionality: 1. Set Up the Voice Bot: • Start by using the
VoicePipelineAgent
or
MultimodalAgent
to manage voice interactions in your LiveKit rooms. • Configure your agent with: ◦ STT: A Speech-to-Text provider like OpenAI STT to convert speech into text. ◦ LLM: A Large Language Model such as OpenAI GPT to understand and process what users say. ◦ TTS: A Text-to-Speech provider to turn responses back into audio. ◦ ChatContext: Set up a shared conversation context to keep track of the chat history smoothly. • Then, get your agent going in a LiveKit room by calling the
start()
method. 2. Create the FastAPI Endpoint: • Build a FastAPI app with a
/chat
POST endpoint to handle text chat. • Let it accept user messages and process them with the same LLM you’re using for the voice bot, keeping things consistent. • Make sure it returns responses structured nicely, including optional details like products, options, and conversation history if needed. 3. Synchronize Voice and Chat: • Share the
ChatContext
between your voice bot and FastAPI endpoint so the conversation stays seamless and up-to-date. • If your setup grows, consider using shared memory or an external store like Redis to keep everything in sync smoothly. 4. Deployment: • Run the LiveKit agent worker to handle all voice interactions reliably. • Host your FastAPI app so users can chat anytime they want. • Double-check network connectivity between the LiveKit agent and FastAPI app to keep things running without a hitch. If you’d like, I’m happy to share some code examples or help you dive deeper into any part of this setup—just let me know!
b
import asyncio import logging from livekit.agents import ( AgentSession, JobContext, JobProcess, WorkerOptions, cli, metrics, AgentFalseInterruptionEvent, RoomInputOptions, UserStateChangedEvent, MetricsCollectedEvent, ) from livekit.plugins import openai, silero, noise_cancellation from src.api.routes import run_fastapi from src.utils.config import ( LLM_MODEL_NAME, LOG_LEVEL, STT_MODEL_NAME, VoiceConfig, LoadBalancingConfig, ) from src.utils.logger import setup_logging from src.voice_assistant import Assistant from dotenv import load_dotenv from src.utils.tts_provider import create_tts load_dotenv() disconnect_task = None def prewarm(proc: JobProcess) -> None: proc.userdata["vad"] = silero.VAD.load( min_speech_duration=VoiceConfig.min_speech_duration, min_silence_duration=VoiceConfig.min_silence_duration, activation_threshold=VoiceConfig.activation_threshold, force_cpu=VoiceConfig.force_cpu, padding_duration=VoiceConfig.padding_duration, max_buffered_speech=VoiceConfig.max_buffered_speech, ) async def entrypoint(ctx: JobContext) -> None: logger = logging.getLogger("support-assistant") logger.info("Initializing support assistant...") await ctx.connect() tts_instance = create_tts() session = AgentSession( llm=openai.LLM(model=LLM_MODEL_NAME), stt=openai.STT(language=VoiceConfig.language, model=STT_MODEL_NAME), tts=tts_instance, vad=ctx.proc.userdata["vad"], preemptive_generation=True, user_away_timeout=5, ) @session.on("user_state_changed") def _on_user_state_changed(ev: UserStateChangedEvent): global disconnect_task if ev.new_state == "away": logger.info("User inactive 30s → asking if they are still there...") session.generate_reply(instructions="ask user if they are still there") # Start a background disconnect timer async def delayed_disconnect(): await asyncio.sleep(15) # wait another 15s # Check if still away if session.user_state == "away": logger.info("No response after warning → disconnecting") try: await ctx.delete_room() except Exception as e: logger.warning( f"Room deletion raised (likely already closed): {e}" ) disconnect_task = asyncio.create_task(delayed_disconnect()) elif ev.new_state == "active": logger.info("User became active again, cancelling pending disconnect") if disconnect_task and not disconnect_task.done(): disconnect_task.cancel() disconnect_task = None @session.on("agent_false_interruption") def _on_false_interrupt(ev: AgentFalseInterruptionEvent): logger.info("False positive interruption detected, resuming...") session.generate_reply(instructions=ev.extra_instructions or "") usage_collector = metrics.UsageCollector() @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) usage_collector.collect(ev.metrics) async def log_usage(): summary = usage_collector.get_summary() logger.info(f"Usage summary: {summary}") ctx.add_shutdown_callback(log_usage) await session.start( agent=Assistant(), room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ), ) try: await session.say( "Hi there! I'm Maya, your voice assistant specialized in personalized skincare consultations. " "Are you looking for skincare products, or a gift for someone?", allow_interruptions=False, ) logger.info("Initial greeting delivered to user") except Exception as e: logger.error(f"Failed to deliver greeting: {e}") if name == "__main__": setup_logging() run_fastapi() worker_opts = WorkerOptions( entrypoint_fnc=entrypoint, load_threshold=LoadBalancingConfig.load_threshold, num_idle_processes=LoadBalancingConfig.num_idle_processes, max_retry=LoadBalancingConfig.max_retry, shutdown_process_timeout=LoadBalancingConfig.shutdown_timeout, initialize_process_timeout=LoadBalancingConfig.initialize_timeout, prewarm_fnc=prewarm, ) cli.run_app(worker_opts) is it possible with my current implementation
t
Your current implementation looks great for creating a voice and chat bot using LiveKit and setting up a FastAPI endpoint for chat functionality. Here’s a quick rundown of how everything fits together: 1. Voice Bot: - You’re spot on with using AgentSession along with STT, LLM, and TTS components. - The prewarm function doing the VAD model preload is a smart move to boost performance. - The entrypoint function nicely initializes the session and manages user state changes smoothly. 2. FastAPI Endpoint: - You can easily add a /chat endpoint to your FastAPI app. - Just use the same LLM from the voice bot to handle user messages and send back responses in the format you want. 3. Synchronization: - Sharing the ChatContext between your voice bot and FastAPI endpoint will keep the conversation history consistent. - If you want to scale, consider using shared memory or an external store like Redis. Next Steps: - Go ahead and add that FastAPI /chat endpoint for text-based chats. - Make sure the ChatContext is shared across both voice and chat interfaces. If you’d like, I’m happy to help with detailed code examples or walk you through any part of this setup. Just let me know! Sources: examples/voice_agents/langgraph_agent.py | LLM Integrations | livekit/livekit_composite | DeepWiki
b
can you add that endpoint for me
t
I can't directly change or add code to your setup, but I’m happy to guide you through the exact steps to add the FastAPI /chat endpoint. Here’s a friendly walkthrough on how you can implement it: 1. Add the Endpoint:
Copy code
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional, List, Dict
from livekit.plugins import openai

app = FastAPI()

class ChatRequest(BaseModel):
    message: str
    chatId: Optional[str] = None

class ChatResponse(BaseModel):
    chatId: str
    response: str
    products: Optional[List[Dict]] = None
    options: Optional[List[str]] = None
    conversationHistory: Optional[List[Dict]] = None
    createdAt: str
    step: Optional[str] = None

# Shared chat context
chat_context = openai.ChatContext()
chat_context.append(role="system", text="You are a helpful assistant.")

@app.post("/chat", response_model=ChatResponse)
async def chat_endpoint(request: ChatRequest):
    # Add user message to the context
    chat_context.append(role="user", text=request.message)

    # Process the message with the LLM
    llm = openai.LLM(model="gpt-4o-mini")
    response = await llm.chat(chat_context)

    # Add assistant’s reply to the context
    chat_context.append(role="assistant", text=response.message.content)

    # Send back the response
    return ChatResponse(
        chatId=request.chatId or "default-chat-id",
        response=response.message.content,
        createdAt=response.created_at,
        conversationHistory=[
            {"role": msg.role, "text": msg.text} for msg in chat_context.messages
        ]
    )
2. Run the FastAPI App: Make sure your FastAPI app is up and running alongside your LiveKit agent worker. You can start the FastAPI server using uvicorn like this:
Copy code
uvicorn src.api.routes:app --host 0.0.0.0 --port 8000
3. Integration: - Double-check that the ChatContext is shared between your voice bot and the FastAPI endpoint. - Try sending some POST requests with user messages to test it out. If you want me to clarify anything or help you test this setup, just let me know—I’m here to help!
b
i got following error File "C:\Users\mayanksingh01\Desktop\livekit\cashmere-ai-support-agent\src\api\routes.py", line 62, in <module> chat_context = openai.ChatContext() ^^^^^^^^^^^^^^^^^^ AttributeError: module 'livekit.plugins.openai' has no attribute 'ChatContext'
t
The error happened because the
ChatContext
class isn’t directly under
livekit.plugins.openai
. It actually lives in the
livekit.agents
module. No worries though, here’s an easy fix for you: 1. Import the Correct Module: Just replace the line where you create
ChatContext
with this:
Copy code
from livekit.agents import ChatContext

chat_context = ChatContext()
chat_context.add_message(role="system", content="You are a helpful assistant.")
2. Update Your Code: Make sure all your
ChatContext
references use this updated import. If you run into any other issues or want a hand with anything else, just let me know! Sources: Large language model (LLM) integrations | LiveKit Docs | LLM Integrations | livekit/livekit_composite | DeepWiki | livekit-agents/livekit/agents/voice/agent.py | agent.py | Workflows | LiveKit Docs
b
File "C:\Users\mayanksingh01\Desktop\livekit\cashmere-ai-support-agent\src\api\routes.py", line 74, in chat_endpoint response = await llm.chat(chat_context) ^^^^^^^^^^^^^^^^^^^^^^ TypeError: LLM.chat() takes 1 positional argument but 2 were given
t
The error happened because the
LLM.chat()
method needs keyword arguments instead of positional ones. No worries, here’s a quick fix for you: Correct Usage:
Copy code
response_stream = llm.chat(chatCtx=chat_context)
Why this works: - You have to pass
chatCtx
as a keyword argument. - The method gives back an async iterable stream of responses. Here’s an example:
Copy code
async for chunk in response_stream:
    if chunk.delta and chunk.delta.content:
        print(chunk.delta.content)
Give this a try, and if you run into any other hiccups, just let me know—I’m here to help! Sources: Large language model (LLM) integrations | LiveKit Docs | livekit-plugins/livekit-plugins-langchain/livekit/plugins/langchain/langgra... | OpenAI LLM integration guide | LiveKit Docs | agents/src/llm/llm.ts
b
File "C:\Users\mayanksingh01\Desktop\livekit\cashmere-ai-support-agent\src\api\routes.py", line 81, in chat_endpoint chat_context.add_message(role="assistant", content=response_stream.message.content) ^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'LLMStream' object has no attribute 'message' got this error
t
The error happened because the
LLMStream
object doesn’t have a
message
attribute. Instead, you’ll want to loop through the stream to get the response chunks. Here’s a friendly little snippet to help you fix it: Correct Usage:
Copy code
async for chunk in response_stream:
    if chunk.delta and chunk.delta.content:
        # Add the assistant’s response to the chat context
        chat_context.add_message(role="assistant", content=chunk.delta.content)
        break  # Stop after the first chunk if you only need one response
Why this works: - The
LLMStream
object is an async iterable that gives you
ChatChunk
objects. - Each
ChatChunk
has a
delta
attribute, which includes the bits of the response as they come in. Give this a try, and if you hit any bumps or have more questions, just let me know—I’m here to help!
b
@app.post("/chat2", response_model=ChatResponse) async def chat_endpoint(request: ChatRequest): # Add user message to the context chat_context.add_message(role="user", content=request.message) # Process the message with the LLM llm = openai.LLM(model="gpt-4.1-mini") response_stream = llm.chat(chat_ctx=chat_context) async for chunk in response_stream: if chunk.delta and chunk.delta.content: print(chunk.delta.content) # Add assistant’s reply to the context chat_context.add_message(role="assistant", content=response_stream.message.content) # Send back the response return ChatResponse( chatId=request.chatId or "default-chat-id", response=response_stream.message.content, createdAt=response_stream.created_at, conversationHistory=[ {"role": msg.role, "content": msg.content} for msg in chat_context.messages ], ) fix in this
t
Here’s the corrected version of your
/chat2
endpoint to handle the
LLMStream
object properly:
Copy code
@app.post("/chat2", response_model=ChatResponse)
async def chat_endpoint(request: ChatRequest):
    # Add user message to the context
    chat_context.add_message(role="user", content=request.message)

    # Process the message with the LLM
    llm = openai.LLM(model="gpt-4.1-mini")
    response_stream = llm.chat(chatCtx=chat_context)

    assistant_response = ""  # Initialize an empty response

    async for chunk in response_stream:
        if chunk.delta and chunk.delta.content:
            assistant_response += chunk.delta.content  # Append the content incrementally

    # Add assistant’s reply to the context
    chat_context.add_message(role="assistant", content=assistant_response)

    # Send back the response
    return ChatResponse(
        chatId=request.chatId or "default-chat-id",
        response=assistant_response,
        createdAt=response_stream.created_at,
        conversationHistory=[
            {"role": msg.role, "content": msg.content} for msg in chat_context.messages
        ],
    )
Fixes Applied: • Switched from using
response_stream.message.content
to a loop that gathers the response bit by bit from the stream. • Created a string variable
assistant_response
to build up the content as it comes in. • Updated the
ChatResponse
to return this full, collected
assistant_response
. If anything’s unclear or you want me to walk you through it, just let me know—I’m here to help!
b
chat_context = ChatContext() chat_context.add_message(role="system", content=ASSISTANT_INSTRUCTIONS) @app.post("/chat2", response_model=ChatResponse) async def chat_endpoint(request: ChatRequest): # Add user message to the context chat_context.add_message(role="user", content=request.message) # Process the message with the LLM llm = openai.LLM(model="gpt-4.1-mini") response_stream = llm.chat(chat_ctx=chat_context) assistant_response = "" # Initialize an empty response async for chunk in response_stream: if chunk.delta and chunk.delta.content: assistant_response += ( chunk.delta.content ) # Append the content incrementally # Add assistant’s reply to the context chat_context.add_message(role="assistant", content=assistant_response) # Send back the response return ChatResponse( chatId=request.chatId or "default-chat-id", response=assistant_response, createdAt="now", conversationHistory=[ {"role": msg.role, "content": msg.content} for msg in chat_context.messages ], ) getting following error File "C:\Users\mayanksingh01\Desktop\livekit\cashmere-ai-support-agent\src\api\routes.py", line 94, in chat_endpoint {"role": msg.role, "content": msg.content} for msg in chat_context.messages
t
""" Hey there! The error happens because the
ChatContext
object doesn’t have a
messages
attribute that you can access the way you’re trying. Instead, you’ll want to use the
items
property of
ChatContext
to loop through the messages. Here’s the updated code for you:
Copy code
# Send back the response
return ChatResponse(
    chatId=request.chatId or "default-chat-id",
    response=assistant_response,
    createdAt="now",
    conversationHistory=[
        {"role": msg.role, "content": msg.content} for msg in chat_context.items
    ],
)
Fix Applied: - Switched out
chat_context.messages
for
chat_context.items
so you can access the conversation history just right. If you have any more questions or need a hand with anything else, just let me know! """
b
thanks i will try and will let you know