When a custom llm call is made, based on a conditi...
# ask-ai
c
When a custom llm call is made, based on a condition I want to push some speech to the end user via livekit as a filler. Does livekit expose any API or webhook to which I can provide text and livekit will take care of converting it into speech and read it out to the user before that actual LLM will start responding?
t
Thanks for reaching out, Bharath. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're covered — LiveKit exposes an API you can call from your agent session to synthesize and play TTS as filler audio. Regarding your specific question: use
session.say()
on the AgentSession to provide text that LiveKit will convert to speech and play to the participant. You can call it before or during your LLM inference. Example:
Copy code
await session.say("Just a moment, I'm working on that.", allow_interruptions=True)
You can control interruption behavior with
allow_interruptions
and whether the text is added to chat context with
add_to_chat_ctx
. No webhook is required — call
session.say()
from your backend during the session. Would you like a short example showing how to call
session.say()
around an LLM request in your codebase language (Python/Node)? Sources: Agent speech and audio | LiveKit docs
c
I should be doing this from my llm service which is differnet from where the livekit sdk is running. So I need an http API to call and push the text.
t
You're asking whether LiveKit offers a public HTTP endpoint you can call from your separate LLM service to push text for TTS playback. LiveKit does not provide a direct HTTP API that accepts text-to-speech requests. To do this you'll need a small bridge service that runs the LiveKit Server SDK (where your AgentSession / LiveKit SDK runs). Options: • Build a bridge endpoint (Node/Python) that your LLM service calls via HTTP with the filler text. The bridge uses the Server SDK to call
session.say()
(or inject into the agent) so LiveKit synthesizes and plays the audio in the room. • If you already run an AgentSession process, add an HTTP listener there to receive text and call
session.say()
with
allow_interruptions
/
add_to_chat_ctx
as needed. If you want, tell me: 1) Which language your LiveKit bridge runs (Node/Python/other), and 2) Whether you need the filler to interrupt current audio or wait for silence. I can then provide a concise example (HTTP route +
session.say()
call) for your stack. Sources: Agent speech and audio | LiveKit docs | server-sdk-js | livekit/livekit_composite | DeepWiki | Text-to-speech (TTS) models | LiveKit Docs
c
My livekit sdk is running in python only and my llm service is also in python so suggest me how and what the bridge in python should look like
t
Responding to: you run LiveKit SDK in Python and need a Python bridge that your LLM service can call to push filler text (TTS) into an AgentSession. Below is a minimal, practical Python bridge using FastAPI that receives HTTP POSTs from your LLM service and calls
session.say()
to play TTS in the room. It shows interrupt handling and optional chat-context addition. 1) Install dependencies:
Copy code
pip install fastapi uvicorn livekit-client  # replace with the actual LiveKit Python SDK package name you use
2) Example bridge (FastAPI):
Copy code
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import asyncio

# Replace these imports with your actual LiveKit AgentSession classes
# from livekit_agent import AgentSession

app = FastAPI()

class TTSRequest(BaseModel):
    session_id: str       # identifier for your AgentSession
    text: str
    allow_interruptions: bool = True
    add_to_chat_ctx: bool = False

# In-memory map of active sessions (replace with your real session store)
SESSIONS = {}  # session_id -> AgentSession instance

@app.post("/play_filler")
async def play_filler(req: TTSRequest):
    # lookup AgentSession
    session = SESSIONS.get(req.session_id)
    if not session:
        raise HTTPException(status_code=404, detail="AgentSession not found")

    try:
        # session.say() is async in the example you were shown
        await session.say(
            req.text,
            allow_interruptions=req.allow_interruptions,
            add_to_chat_ctx=req.add_to_chat_ctx
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

    return {"status": "ok", "played_text": req.text}
3) How to wire sessions into SESSIONS: • When your LiveKit service creates or accepts an AgentSession, store it in SESSIONS with a unique
session_id
that your LLM service can reference. Example strategies: ◦ Generate a UUID per room/interaction and return it to the LLM service when the session starts. ◦ Use the LiveKit room ID or agent ID if unique. 4) Example flow from your LLM service: • POST to /play_filler with JSON: { "session_id": "...", "text": "Just a moment, I'm working on that.", "allow_interruptions": true, "add_to_chat_ctx": false } 5) Notes and recommendations: • Ensure the bridge process is the process that owns the AgentSession and has access to the LiveKit SDK. • If sessions can time out, remove them from SESSIONS and return appropriate 404s. • Add authentication (API keys/JWT) to the bridge endpoint to prevent unauthorized TTS injection. • If you need higher scale or persistence, store sessions in a shared store (Redis) or route requests to the correct process (service discovery). If you want, I can: • Provide a fuller example showing how to create and store an
AgentSession
when a room starts, or • Convert the example to Flask or show request signing/auth. Which would you prefer?
c
Yes, please provider a fuller example showing how to create and store an
AgentSession
when a room starts
t
Responding to: provide a fuller Python example showing how to create and store an
AgentSession
when a room starts, and expose an HTTP API to receive filler text from your LLM service. Below is a practical, minimal example using FastAPI. It shows: • Creating an
AgentSession
when a user/room starts (simulated via an endpoint). • Storing sessions in an in-memory registry. • An endpoint
/play_filler
your LLM service can POST to, which calls
session.say()
to synthesize and play TTS. • Basic session cleanup and simple auth placeholder. Adjust imports and session creation to match your LiveKit AgentSession API if names differ. 1) Install:
Copy code
pip install fastapi uvicorn
# plus your LiveKit Python SDK / agent package
2) Example app:
Copy code
import asyncio
import uuid
from fastapi import FastAPI, HTTPException, Header, Depends
from pydantic import BaseModel
from typing import Dict, Optional

# Replace with your actual AgentSession import
# from livekit_agent import AgentSession

app = FastAPI()
# In-memory sessions: session_id -> AgentSession
SESSIONS: Dict[str, "AgentSession"] = {}
# Simple API key for auth (replace with real auth)
API_KEY = "replace_with_secure_key"

class CreateSessionRequest(BaseModel):
    room_name: str
    participant_identity: str

class TTSRequest(BaseModel):
    session_id: str
    text: str
    allow_interruptions: bool = True
    add_to_chat_ctx: bool = False

def require_api_key(x_api_key: Optional[str] = Header(None)):
    if x_api_key != API_KEY:
        raise HTTPException(status_code=401, detail="Unauthorized")

# --- Helpers to create/destroy AgentSession ---
async def create_agent_session(room_name: str, participant_identity: str) -> "AgentSession":
    """
    Create and return an AgentSession connected to the given room/participant.
    Adjust this to match how you construct AgentSession in your SDK.
    """
    # Example placeholder: replace with real session creation code
    # session = AgentSession(room=room_name, identity=participant_identity, tts_plugin="default")
    session = DummyAgentSession(room_name, participant_identity)  # replace in real code
    await session.connect()
    return session

async def destroy_agent_session(session_id: str):
    session = SESSIONS.get(session_id)
    if not session:
        return
    try:
        await session.disconnect()
    finally:
        SESSIONS.pop(session_id, None)

# --- Endpoints ---

@app.post("/start_session", dependencies=[Depends(require_api_key)])
async def start_session(req: CreateSessionRequest):
    session_id = str(uuid.uuid4())
    try:
        session = await create_agent_session(req.room_name, req.participant_identity)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to create session: {e}")

    # store session
    SESSIONS[session_id] = session

    return {"session_id": session_id, "room": req.room_name}

@app.post("/end_session", dependencies=[Depends(require_api_key)])
async def end_session(session_id: str):
    if session_id not in SESSIONS:
        raise HTTPException(status_code=404, detail="Session not found")
    await destroy_agent_session(session_id)
    return {"status": "ended", "session_id": session_id}

@app.post("/play_filler", dependencies=[Depends(require_api_key)])
async def play_filler(req: TTSRequest):
    session = SESSIONS.get(req.session_id)
    if not session:
        raise HTTPException(status_code=404, detail="AgentSession not found")

    try:
        # Call session.say() — adjust kwargs if your SDK differs
        await session.say(
            req.text,
            allow_interruptions=req.allow_interruptions,
            add_to_chat_ctx=req.add_to_chat_ctx
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to play filler: {e}")

    return {"status": "ok", "played_text": req.text}

# Optional: endpoint to list sessions (debug)
@app.get("/sessions", dependencies=[Depends(require_api_key)])
def list_sessions():
    return {"active_sessions": list(SESSIONS.keys())}

# --- DummyAgentSession for illustrative purposes only ---
class DummyAgentSession:
    def __init__(self, room, identity):
        self.room = room
        self.identity = identity
        self.connected = False

    async def connect(self):
        # Simulate async connect
        await asyncio.sleep(0.1)
        self.connected = True

    async def say(self, text, allow_interruptions=True, add_to_chat_ctx=False):
        if not self.connected:
            raise RuntimeError("Session not connected")
        # Replace this with real TTS call in your AgentSession
        print(f"[TTS -> room:{self.room} id:{self.identity}] {text}")

    async def disconnect(self):
        await asyncio.sleep(0.05)
        self.connected = False
3) Usage flow: • When a LiveKit room/participant starts, call POST /start_session with room_name and participant_identity to create and store an AgentSession; keep the returned
session_id
. • Your LLM service posts to /play_filler with that
session_id
and text; the bridge calls
session.say()
and LiveKit plays TTS into the room. • Call /end_session to clean up when the interaction finishes. 4) Production notes (implement these for real deployments): • Replace DummyAgentSession with your real LiveKit
AgentSession
creation logic and connection parameters. • Secure endpoints with strong auth (JWTs, mTLS) and validate caller permissions. • Use a persistent or shared session registry (Redis) if you run multiple bridge processes; route requests to the correct process. • Handle session timeouts, reconnection logic, and errors from the TTS plugin. • Rate-limit calls from the LLM service to avoid audio overlap or excessive TTS usage. Would you like the real AgentSession creation snippet adjusted to your LiveKit SDK code (share the constructor signature you use) or a version that uses Redis for shared sessions?
c
how do I persist these sessions? since these are in memory they can be lost when app crashes or when there are multiple replicas of the sdk
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
using livekit sdk, is there a way that I can get access to the
session
object when I pass a session ID?