wonderful-kilobyte-85140
12/01/2025, 5:09 AMtall-airline-16756
12/01/2025, 5:09 AMtall-airline-16756
12/01/2025, 5:10 AMwonderful-kilobyte-85140
12/01/2025, 5:11 AMtall-airline-16756
12/01/2025, 5:11 AMwonderful-kilobyte-85140
12/01/2025, 5:15 AMtall-airline-16756
12/01/2025, 5:16 AMagent-starter-python/
├── src/
│ ├── agent.py # entry: registers job handler, starts worker
│ ├── voice_agent.py # per-job logic: connect to room, pipeline (VAD/STT/LLM/TTS)
│ ├── stt_client.py # adapter for chosen STT (streaming)
│ ├── tts_client.py # adapter for chosen TTS (streaming)
│ ├── llm_client.py # adapter for LLM provider & prompt manager
│ ├── utils/
│ │ ├── vad.py
│ │ ├── audio_io.py # WAV/opus frames, buffering
│ │ └── telemetry.py
├── Dockerfile
├── .env.example # env vars: LIVEKIT_KEY/SECRET, STT/TTS/LLM keys
├── pyproject.toml
└── tests/
• Node.js variant is analogous:
◦ src/index.js (worker bootstrap)
◦ src/agent.js (job handler)
◦ provider adapters under src/providers/*
◦ package.json, Dockerfile, .env.example
Key runtime behaviors
• Worker process registers with LiveKit Agents framework and exposes a job handler.
• When a job arrives, spawn an isolated job context (task/thread/async task) that:
a. Connects to the specified LiveKit room as a participant (mic + speaker).
b. Subscribes to remote audio tracks and uses VAD to cut speech segments.
c. Streams audio chunks to STT; receives interim/final transcripts.
d. Passes transcripts + convo context to LLM (streaming if available).
e. Streams LLM output to TTS and publishes audio track(s) back.
f. Persists transcripts/recording metadata and emits webhooks/events.
• Provide graceful shutdown: finish active jobs or checkpoint, close streams, deregister.
• Expose health endpoint (/health) and basic metrics (active_jobs, cpu, mem).
Agent orchestrator — how the repo/infrastructure looks
• Purpose: manage worker deployment, autoscaling, health checks, and versioned releases.
• Two deployment models:
a. LiveKit Cloud (managed) — CLI-driven deploys; less infra work.
b. Self-hosted (Kubernetes) — full control; typical production choice.
Typical infra repo layout (Kubernetes / GitOps)
agents-infra/
├── charts/ # Helm charts for agent service
│ └── agent/
│ ├── templates/deployment.yaml
│ ├── templates/hpa.yaml
│ └── values.yaml
├── k8s/
│ ├── namespace.yaml
│ └── secrets.yaml # reference to .env (from CI/CD secret store)
├── ci/
│ ├── pipeline.yaml # build image, run tests, push image
│ └── deploy.yaml # deploy to cluster via helm
└── README.md
Orchestrator responsibilities / configs
• Deployment (Deployment/StatefulSet):
◦ Container image built from agent repo Dockerfile.
◦ Readiness/Liveness probes: /health and optionally /ready.
◦ terminationGracePeriodSeconds set high (allow active calls to finish).
• Autoscaling:
◦ Horizontal Pod Autoscaler (HPA) based on custom metrics (active_jobs, CPU) or KEDA for event-driven scaling.
◦ Scale-up threshold lower than worker `load_threshold`; scale-down cooldown to avoid killing active calls.
• Load & job acceptance:
◦ Each worker reports a load function (CPU or custom metric). LiveKit (or the orchestrator) uses this to decide whether to dispatch jobs to that worker.
• Versioning & rollout:
◦ Rolling updates with graceful drain (stop accepting new jobs, wait for active jobs to finish).
◦ Blue/green or canary via Helm values and labels.
• Observability:
◦ Export metrics (Prometheus): active_jobs, job_duration_seconds, stt_latency, tts_latency.
◦ Centralized logs and traces (ELK / Datadog / Tempo).
• High availability:
◦ Multi‑AZ or multi‑region clusters; colocate agents near SIP trunks or user population for lower latency.
Concrete operational notes
• Health check endpoints must reflect ability to accept new jobs (e.g., return unhealthy when load > load_threshold).
• Worker image should include a small supervisor script to restart crashed tasks and to ensure graceful signal handling.
• Keep secrets out of the image; inject via k8s secrets or the managed platform’s secret store.
• For SIP bridging, run a small stateless service that converts SIP <-> WebRTC and creates the LiveKit room; this service can live in same infra repo.
If you want, I can:
• Produce a minimal POC repo skeleton (Dockerfile + basic agent.py job handler + k8s manifests) you can fork, or
• Show a concrete job handler code snippet (Python) that demonstrates subscribing to audio, streaming to STT, and publishing TTS audio back.
Which would help you next?
Sources: Deploying to custom environments | LiveKit Docs | An open source stack for real-time multimodal AI | livekit/livekit_composite | DeepWiki | Agents (Python) | livekit/livekit_composite | DeepWiki | examples/frontdesk | livekit/livekit_composite | DeepWikiwonderful-kilobyte-85140
12/01/2025, 5:32 AMtall-airline-16756
12/01/2025, 5:32 AMwonderful-kilobyte-85140
12/01/2025, 5:37 AMtall-airline-16756
12/01/2025, 5:38 AMstart_stream() → returns a stream object
◦ async push_frame(frame) → send audio frames
◦ async end_stream() → finish input
◦ async iterator or callback for transcript/response events
◦ close() / cleanup
Example STT adapter (Deepgram-like)
# src/adapters/stt/deepgram_adapter.py
class DeepgramSTTAdapter:
def __init__(self, api_key, model="nova-2"):
self.api_key = api_key
self.model = model
async def start_stream(self):
# open websocket / streaming client to provider
self.stream = DeepgramClient(self.api_key, model=self.model).open_stream()
return self.stream
async def push_frame(self, pcm_frame: bytes):
await self.stream.send_audio(pcm_frame)
async def end_stream(self):
await self.stream.finish_input()
async def results(self):
# async iterator yielding transcript events
async for ev in self.stream:
yield ev
async def close(self):
await self.stream.close()
Example LLM adapter (OpenAI-like)
# src/adapters/llm/openai_adapter.py
class OpenAIAdapter:
def __init__(self, api_key, model="gpt-4o-mini"):
self.api_key = api_key
self.model = model
async def generate(self, prompt, stream=False):
if stream:
# return async generator of partial tokens
async for chunk in openai_client.stream_completion(self.api_key, self.model, prompt):
yield chunk
else:
return await openai_client.complete(self.api_key, self.model, prompt)
Example TTS adapter (ElevenLabs-like)
# src/adapters/tts/elevenlabs_adapter.py
class ElevenLabsTTSAdapter:
def __init__(self, api_key, voice="alloy"):
self.api_key = api_key
self.voice = voice
async def synthesize_stream(self, text):
# returns async iterator of audio chunks (pcm/opus)
async for audio_chunk in eleven_client.stream_tts(self.api_key, self.voice, text):
yield audio_chunk
How your agent uses adapters (pseudo-workflow)
1. job starts → create adapters from config (stt = DeepgramSTTAdapter(...), llm = OpenAIAdapter(...), tts = ElevenLabsTTSAdapter(...))
2. stt_stream = await stt.start_stream()
3. while receiving audio frames from LiveKit:
◦ feed frames into stt.push_frame(frame)
◦ read interim transcripts from stt.results() and update convo context
1. when end-of-turn detected, assemble prompt and call llm.generate(prompt, stream=True)
2. stream llm output into tts.synthesize_stream(...) and publish audio chunks back to LiveKit
3. persist transcripts/metadata, close adapters
Benefits in code
• Agent core only calls the small adapter API — switching providers is just instantiating a different adapter class.
• Fallbacks: wrap adapters in a FallbackAdapter([primary, backup]) that tries next on errors.
• Easier to mock in tests: replace adapters with in-memory implementations.
If you want, I can:
• generate a minimal repo scaffold (Python) with one STT, one LLM, one TTS adapter + a simple job handler that wires them together, or
• produce a concrete code example showing the async loop that reads LiveKit audio, sends to STT, calls LLM, and streams TTS back.
Which would you prefer?
Sources: Agents (Python) | livekit/livekit_composite | DeepWiki | Text-to-speech (TTS) models | LiveKit Docs | server-sdk-js | livekit/livekit_composite | DeepWiki | Agents Framework | livekit/livekit_composite | DeepWiki | Models | LiveKit Docswonderful-kilobyte-85140
12/01/2025, 5:40 AMtall-airline-16756
12/01/2025, 5:41 AMAgentSession / plugin classes) so your job handler calls a consistent interface (start_stream, push_frame, end_stream, async results, synthesize_stream).
• Convenience features: string-based model/provider shorthand for LiveKit Inference (e.g., "assemblyai/universal-streaming:en"), fallback adapters, and plugin registration.
When you don’t need custom adapters
• You use supported cloud vendors and the framework’s plugin classes or the Inference string syntax.
• You want standard streaming STT → LLM → TTS flows with typical provider options and sensible defaults.
When you do need a custom adapter
• You require a vendor not supported by the framework, or need nonstandard auth/protocols.
• You need special behaviors (custom retry/backoff, audio pre/post processing, bespoke streaming semantics).
• You want to mock or simulate provider behavior for advanced tests beyond built-in mocks.
Practical choices
• Fast path (recommended for POC): use built-in plugins or Inference strings in your AgentSession — no adapter code needed.
• Production/customization: use provided adapters but wrap them with small glue classes (or implement one) for feature toggles, telemetry, and fallback logic.
If you want, I can:
• Show the minimal config / code that wires built-in plugins into an AgentSession (Python or Node), or
• Generate a tiny custom adapter example (if you plan a provider not yet supported).
Which would you like?