Internal Tool
# ask-ai
m
Internal Tool
t
Thanks for reaching out, aigentzi. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I can help with your internal tool. Could you tell me a bit more about what you need? • Are you asking about setup, a bug, a feature request, access/permissions, or something else? • Which environment or project is this for (project ID, room ID, or app name)? • Any error messages, steps to reproduce, or screenshots you can share? Share whichever details you have and I’ll guide you through next steps.
m
Need coding help: Internal Retell/Vapi-like platform on LiveKit Cloud Scale + Inference Building an internal voice AI infrastructure to power our own apps — our own Retell/Vapi stack. Stack (decided): • LiveKit Cloud Scale • LiveKit Inference for STT/LLM/TTS • SIP trunks for phone support Agent types we'll support (configurable): • Interviewer • Coach • Trainer • Language tutor • Others as needed Capabilities vary by agent type: • Voice-only vs video-enabled • With/without recording • With/without meeting rooms (multi-participant) What we need help with: 1. Repo structure that supports multiple configurable agent types 2. Base
agent.py
pattern using Inference + built-in plugins (VAD → STT → LLM → TTS) 3. How to parameterize agents (voice-only vs video, recording on/off, single vs multi-participant) 4. Room configuration patterns for different modes 5. SIP trunk setup for phone connectivity 6. Deployment config for Cloud Scale Looking for concrete code patterns and examples.
t
Thanks — this is a great brief. I’ll help you with concrete, reusable code patterns and configuration guidance that map to each item you listed. Before I produce the full examples (repo layout, base
agent.py
, config schema, room patterns, SIP config, and Cloud Scale deploy files), one quick clarifying question so I don’t guess on details: • Do you want the examples in Python (LiveKit Agents Python) or Node.js? Reply with your preference and I’ll provide a focused, copy‑pasteable set of files and deployment steps. Sources: Agents (Python) | livekit/livekit_composite | DeepWiki | Examples | livekit/livekit_composite | DeepWiki | Agents (Node.js) | livekit/livekit_composite | DeepWiki | Voice AI quickstart | LiveKit docs | Models | LiveKit Docs
m
python we will be 'all in' with livkekit cloud Scale and inference
t
Great — here’s a focused, copy‑pasteable Python-first blueprint that covers your requested areas: repo structure, base agent pattern (VAD → STT → LLM → TTS), agent parameterization, room configs, SIP trunk basics, and Cloud Scale deployment files. Each file is short and practical so you can iterate quickly. Repository layout • internal-voice-agent/ ◦ agents/ ▪︎ init.py ▪︎ base_agent.py ▪︎ interviewer.py ▪︎ coach.py ▪︎ tutor.py ▪︎ tools/ • recorder.py ◦ config/ ▪︎ agent_configs.json ▪︎ room_configs.json ◦ deployment/ ▪︎ livekit.us-east.toml ▪︎ livekit.eu-central.toml ◦ agent_entry.py ◦ Dockerfile ◦ .env.sample ◦ README.md 1) config/agent_configs.json (sample)
Copy code
{
  "interviewer": {
    "instructions": "You are a technical interviewer. Ask one question at a time.",
    "voice": "onyx",
    "stt": "assemblyai/universal-streaming:en",
    "llm": "openai/gpt-4.1-mini",
    "tts": "cartesia/sonic-3:default",
    "enable_video": false,
    "enable_recording": true,
    "room_mode": "single_participant"
  },
  "tutor": {
    "instructions": "Teach language interactively. Correct pronunciation.",
    "voice": "fable",
    "stt": "assemblyai/universal-streaming:en",
    "llm": "openai/gpt-4.1-turbo",
    "tts": "cartesia/sonic-3:default",
    "enable_video": true,
    "enable_recording": false,
    "room_mode": "multi_participant"
  }
}
2) agents/base_agent.py
Copy code
import json
from typing import Dict, Any
from livekit import agents
from livekit.agents import AgentContext, JobContext
from livekit.agents.voice import AgentSession
from livekit.plugins import silero, noise_cancellation
from livekit.plugins.turn_detector.multilingual import MultilingualModel

CONFIG = json.load(open("config/agent_configs.json"))

class BaseVoiceAgent(agents.Agent):
    def __init__(self, instructions: str):
        super().__init__(instructions=instructions)

async def build_session_for_config(config: Dict[str, Any]) -> AgentSession:
    # Build an AgentSession that wires VAD -> STT -> LLM -> TTS
    session = AgentSession(
        stt=config["stt"],
        llm=config["llm"],
        tts=config["tts"],
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
        voice_options={"voice": config.get("voice")},
    )
    # Optional audio preprocessing
    session.input.set_noise_cancellation(noise_cancellation.BVC())
    return session
3) agents/interviewer.py (example subclass)
Copy code
from .base_agent import BaseVoiceAgent, build_session_for_config, CONFIG
from livekit.agents import JobContext

class InterviewerAgent(BaseVoiceAgent):
    def __init__(self, config):
        super().__init__(instructions=config["instructions"])
        self.config = config

async def entrypoint(job: JobContext):
    config = CONFIG["interviewer"]
    session = await build_session_for_config(config)
    agent = InterviewerAgent(config)
    room_opts = make_room_options(config)
    await session.start(agent=agent, room=job.room, room_options=room_opts)
    await session.generate_reply(instructions="Greet the candidate as an interviewer.")
4) agents/coach.py and agents/tutor.py • Implement same pattern as interviewer.py but load different config and optionally add tools (recorder, analytics). 5) agents/tools/recorder.py (egress helper)
Copy code
import asyncio
from livekit import api

async def start_egress_for_room(room_name: str, outputs: dict):
    lk_api = api.LiveKitAPI()
    await lk_api.room.create_room_composite_egress(
        room_name=room_name,
        file_outputs=[api.FileOutputs(s3=api.S3Upload(**outputs))]
    )
6) agent_entry.py (CLI entrypoint to run agent)
Copy code
import os
import json
import asyncio
from livekit import agents
from livekit.agents import JobContext
from agents.interviewer import entrypoint as interviewer_entry

AGENT_TYPE = os.getenv("AGENT_TYPE", "interviewer")
CONFIG = json.load(open("config/agent_configs.json"))

ENTRYPOINT_MAP = {
    "interviewer": interviewer_entry,
    # "coach": coach_entry, "tutor": tutor_entry
}

if __name__ == "__main__":
    agents.cli.run_app(
        agent_class=agents.JobType.JT_ROOM,
        entrypoint_fnc=ENTRYPOINT_MAP[AGENT_TYPE]
    )
7) Room configuration helpers (inline pattern) • make_room_options used in agent files:
Copy code
from livekit.agents.voice import room_io
from livekit.plugins import noise_cancellation

def make_room_options(config):
    return room_io.RoomOptions(
        audio_input=room_io.AudioInputOptions(
            noise_cancellation=noise_cancellation.BVC()
        ),
        video_input=config.get("enable_video", False),
        audio_output=True,
        text_output=True,
    )
8) Parameterization patterns • Use config JSON and runtime env var AGENT_TYPE. • Toggle features in code using config keys: ◦ enable_video -> set video_input True/False ◦ enable_recording -> call start_egress_for_room when job starts ◦ room_mode: ▪︎ single_participant: on participant_connected, remove extras or refuse join ▪︎ multi_participant: allow all, optionally instantiate per-participant contexts Example participant guard (single-participant):
Copy code
@job.on("participant_connected")
async def handle_join(ctx: JobContext, participant):
    config = CONFIG[os.getenv("AGENT_TYPE", "interviewer")]
    if config["room_mode"] == "single_participant" and len(ctx.room.participants) > 1:
        await ctx.room.local_participant.remove_participant(participant)
9) SIP trunk setup (high-level commands/examples) • Provision a provider trunk (e.g., Twilio) and configure LiveKit inbound trunk: ◦ Create Twilio trunk per provider docs, enable TLS/SRTP. ◦ Create inbound trunk JSON and register via lk CLI: ▪︎ twilio-inbound.json:
Copy code
{
  "name": "Twilio US Inbound",
  "numbers": [
    "+15105550100"
  ],
  "krisp_enabled": true
}
• CLI: ◦ lk sip inbound create twilio-inbound.json • Create dispatch rule to route numbers to room prefixes (e.g., interview_{id}) and configure agent dispatch mapping. • When a SIP call arrives, LiveKit dispatches to an agent job with a room name per rule; your agent's entrypoint receives JobContext and can answer. 10) Deployment for Cloud Scale (livekit CLI patterns) • .env.sample:
Copy code
LIVEKIT_API_KEY=...
LIVEKIT_API_SECRET=...
OPENAI_API_KEY=...
AGENT_TYPE=interviewer
• deployment/livekit.us-east.toml:
Copy code
[project]
subdomain = "your-project"

[agent]
id = "CA_youragentid"
• Commands: ◦ lk agent create --region us-east --config deployment/livekit.us-east.toml --secrets-file .env.sample ◦ lk agent deploy --config deployment/livekit.us-east.toml ◦ For multi-region, create per-region toml and run create/deploy per region. • Use AGENT_TYPE env override to deploy different agent roles or set runtime metadata to route dispatch rules. 11) Dockerfile (simple)
Copy code
FROM python:3.11-slim
WORKDIR /app
COPY pyproject.toml ./
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "agent_entry.py"]
12) Best practices & next steps • Keep agents stateless; store session state externally (DB) if needed. • Use AgentSession for unified VAD→STT→LLM→TTS flow. • Use egress for recordings to S3/GCS when enable_recording true. • Add observability: Cloud Scale logs, metrics. If you’d like, I can now: • Produce full ready-to-run code files (complete interviewer/coach/tutor) including imports and minimal requirements.txt; or • Provide a Docker + lk CLI deploy script and example dispatch rules for SIP mapping. Which of those would you like next?
m
Our Serverless Tech Stack • LiveKit Cloud • Neon (Serverless Postgres) • Vercel • QStash • Redis KV
t
Thanks — you’ve shared your serverless stack. Quick question so I provide the most useful integrations and examples: Which integration would you like first (pick one or more)? • Neon (Postgres schema examples for sessions/records) • Vercel (frontend + serverless API to get join tokens) • QStash (reliable background job webhook delivery / egress notifications) • Redis KV (fast ephemeral state: turn control, presence, rate limits) • Or a full end-to-end example wiring all of the above Pick one and I’ll produce concrete, copy‑pasteable code and config tailored to LiveKit Cloud + Inference in Python.
m
• Or a full end-to-end example wiring all of the above
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!