straight-greece-72452
12/05/2025, 2:10 PMtall-airline-16756
12/05/2025, 2:10 PMtall-airline-16756
12/05/2025, 2:10 PMstraight-greece-72452
12/05/2025, 2:31 PMtall-airline-16756
12/05/2025, 2:31 PMstraight-greece-72452
12/05/2025, 2:33 PMtall-airline-16756
12/05/2025, 2:33 PMlivekit_agents with those classes. I can:
• Provide a small runnable example that uses the LiveKit Python SDK for room signaling (token generation) and the OpenAI Realtime WebSocket API for model responses, or
• Provide a minimal example that relies on the LiveKit Agents examples repo (which contains working code) and point to the exact file to run.
Which do you prefer?
• Option A — a standalone single-file Python example that uses LiveKit server JWTs (via the official LiveKit Python JWT helper) plus a WebSocket connection to OpenAI Realtime for text-based conversation (no advanced agent framework). This will be fully runnable and minimal.
• Option B — a pointer to the exact minimal example in the LiveKit agents repo (ready-to-run with that repo’s helper classes) and I’ll copy the smallest working file for you and include exact install commands.
Pick A or B and I’ll produce the code and install/env steps.straight-greece-72452
12/05/2025, 2:40 PMtall-airline-16756
12/05/2025, 2:41 PMstraight-greece-72452
12/05/2025, 2:44 PMtall-airline-16756
12/05/2025, 2:44 PM# repo_example.py (verbatim from LiveKit agents docs)
from dotenv import load_dotenv
from livekit import agents, rtc
from livekit.agents import AgentServer, AgentSession, Agent, room_io
from livekit.plugins import openai, noise_cancellation
load_dotenv('.env.local')
class Assistant(Agent):
def __init__(self) -> None:
super().__init__(instructions="You are a helpful voice AI assistant.")
server = AgentServer()
@server.rtc_session()
async def my_agent(ctx: agents.JobContext):
session = AgentSession(
llm=openai.realtime.RealtimeModel(
voice="coral"
)
)
await session.start(
room=ctx.room,
agent=Assistant(),
room_options=room_io.RoomOptions(
audio_input=room_io.AudioInputOptions(
noise_cancellation=lambda params: noise_cancellation.BVCTelephony()
if params.participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP
else noise_cancellation.BVC(),
),
),
)
await session.generate_reply(
instructions="Greet the user and offer your assistance. You should start by speaking in English."
)
if __name__ == "__main__":
agents.cli.run_app(server)
Notes for the verbatim example:
• Requires livekit-agents[openai] and livekit-plugins-noise-cancellation.
• Place OpenAI key in .env.local as OPENAI_API_KEY.
2) Simplified single-file runnable example
# agent.py - Minimal, runnable OpenAI Realtime Agent (single file)
from dotenv import load_dotenv
import asyncio
from livekit.agents import AgentContext, JobContext, WorkerOptions, cli
from livekit.plugins import openai
load_dotenv('.env.local')
async def entrypoint(ctx: JobContext):
# Create a simple AgentContext and session using OpenAI RealtimeModel
context = AgentContext()
session = context.create_session(
llm=openai.realtime.RealtimeModel(
voice="alloy",
temperature=0.7,
instructions="You are a friendly AI assistant. Keep replies short."
)
)
# Connect session to the room and start listening/responding
await session.connect(ctx.room)
# Optional initial greeting
await session.generate_reply(instructions="Greet the user warmly and offer help.")
# Keep running while connected
while ctx.room.connection_state == ctx.room.ConnectionState.CONNECTED:
await asyncio.sleep(1)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Setup and run (both examples)
• Install packages:
◦ uv: uv add "livekit-agents[openai]~=1.2" livekit-plugins-noise-cancellation python-dotenv
• Create .env.local with:
OPENAI_API_KEY=your_openai_api_key_here
• Run:
◦ For repo-style server: python repo_example.py dev (or uv run repo_example.py dev if using uv)
◦ For single-file agent: uv run agent.py dev
If you’d like, I can:
• Paste the exact repository file path/name where the verbatim example lives, or
• Add a minimal .env.local example that includes LiveKit-specific env vars if you plan to run against a specific LiveKit deployment. Which would you prefer? Sources: Voice AI quickstart | LiveKit docs | OpenAI and LiveKit partner to turn Advanced Voice into an APIstraight-greece-72452
12/05/2025, 2:49 PMtall-airline-16756
12/05/2025, 2:49 PMstraight-greece-72452
12/05/2025, 5:39 PMtall-airline-16756
12/05/2025, 5:40 PM# realtime_translator.py
import os
import asyncio
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit import rtc
from livekit.plugins import deepgram, openai
load_dotenv(".env.local")
# Target language for translation
TARGET_LANG = "es" # Spanish
async def entrypoint(ctx: JobContext):
await ctx.connect(auto_subscribe=rtc.AutoSubscribe.AUDIO_ONLY)
# Configure streaming STT with interim results
stt = deepgram.STT(api_key=os.environ["DG_API_KEY"], interim_results=True, model="nova-2")
# Simple OpenAI LLM wrapper for translation
llm = openai.LLM(api_key=os.environ["OPENAI_API_KEY"], model="gpt-4o")
async def handle_track(track: rtc.RemoteTrack, _participant):
if track.kind != rtc.TrackKind.KIND_AUDIO:
return
# Create an audio stream from the remote track (SDK helper)
audio_stream = rtc.AudioStream(track)
async def stt_reader():
async for ev in stt.stream(audio_stream): # yields interim/final transcript events
if not ev.alternatives:
continue
text = ev.alternatives[0].text.strip()
if not text:
continue
# Translate short interim text (keep payload small)
prompt = [
{"role": "system", "content": f"Translate the following text to {TARGET_LANG}. Return only the translation."},
{"role": "user", "content": text}
]
try:
resp = await llm.chat(messages=prompt)
translated = resp.choices[0].message.content.strip()
except Exception as e:
translated = f"[translation error]"
# Publish translated text to room as a data message on topic "translation"
await ctx.room.local_participant.publish_data(translated, topic="translation")
asyncio.create_task(stt_reader())
# Subscribe to incoming tracks
@ctx.room.on("track_subscribed")
async def on_track_subscribed(track, participant):
await handle_track(track, participant)
# Keep the agent alive while connected
while ctx.room.connection_state == rtc.ConnectionState.CONN_CONNECTED:
await asyncio.sleep(1)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
2) .env.local (required)
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
LIVEKIT_URL=wss://<your-project>.livekit.cloud
OPENAI_API_KEY=your_openai_api_key
DG_API_KEY=your_deepgram_api_key
3) Install
• Using uv:
uv add "livekit-agents[openai,deepgram]~=1.2" python-dotenv
4) Run (local dev)
• uv run realtime_translator.py dev
5) Frontend: receive translations
• Clients subscribe to LiveKit data messages. Listen for data messages with topic "translation" and render the text immediately (these will be interim translations while the user speaks).
Notes and recommendations
• Interim STT generates many short chunks; you may want to debounce/throttle translations or apply simple heuristics to avoid excessive LLM calls (e.g., only translate every 500–1000ms or when punctuation/boundary is detected).
• This example sends translated text as data messages. If you want spoken translations, add a TTS step (LLM→TTS plugin or OpenAI Realtime TTS) and publish audio into the room.
• If you prefer the OpenAI Realtime model for everything: it does not provide interim transcripts while the user is speaking, so it cannot translate "while" the user speaks without a separate streaming STT source.
Would you like this adapted to emit spoken translations (TTS) instead of data messages, or a version with simple throttling to reduce API calls?
Sources: Realtime model plugins | LiveKit Docs | Speech-to-text (STT) models | LiveKit Docs | LiveKit Docsstraight-greece-72452
12/06/2025, 8:45 AMtall-airline-16756
12/06/2025, 8:46 AM# realtime_translator.py
import os
import asyncio
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit import rtc
from livekit.plugins import deepgram, openai
load_dotenv(".env.local")
TARGET_LANG = "es" # target language code, e.g. "es" for Spanish
async def entrypoint(ctx: JobContext):
await ctx.connect(auto_subscribe=rtc.AutoSubscribe.AUDIO_ONLY)
# STT: Deepgram streaming with interim results
stt = deepgram.STT(api_key=os.environ["DG_API_KEY"], model="nova-2", interim_results=True)
# LLM: OpenAI for translation
llm = openai.LLM(api_key=os.environ["OPENAI_API_KEY"], model="gpt-4o")
async def handle_audio_track(track: rtc.RemoteTrack, _participant):
if track.kind != rtc.TrackKind.KIND_AUDIO:
return
# Wrap track into an audio stream helper the STT expects
audio_stream = rtc.AudioStream(track)
async def stream_and_translate():
async for ev in stt.stream(audio_stream): # yields interim + final transcript events
if not ev.alternatives:
continue
text = ev.alternatives[0].text.strip()
if not text:
continue
# Build a minimal prompt to translate; return only translation
prompt = [
{"role": "system", "content": f"Translate to {TARGET_LANG}. Return only the translated text."},
{"role": "user", "content": text}
]
try:
resp = await llm.chat(messages=prompt)
translated = resp.choices[0].message.content.strip()
except Exception:
translated = "[translation_error]"
# Publish translated interim text to room as data message
await ctx.room.local_participant.publish_data(translated, topic="translation")
asyncio.create_task(stream_and_translate())
@ctx.room.on("track_subscribed")
async def on_track_subscribed(track, participant):
await handle_audio_track(track, participant)
# keep agent alive while connected
while ctx.room.connection_state == rtc.ConnectionState.CONN_CONNECTED:
await asyncio.sleep(1)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
.env.local (required)
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
LIVEKIT_URL=wss://<your-project>.livekit.cloud
OPENAI_API_KEY=your_openai_api_key
DG_API_KEY=your_deepgram_api_key
Install
• uv add "livekit-agents[openai,deepgram]~=1.2" python-dotenv
Run locally (dev)
• uv run realtime_translator.py dev
How it works (short)
• Deepgram streams interim transcripts as the user speaks.
• Each interim chunk is sent to OpenAI LLM for translation.
• Translated text is pushed immediately to clients via LiveKit data messages (topic "translation").
Notes and tips
• Interim chunks are frequent — add throttling/debouncing (e.g., translate only every 500–1000ms or when punctuation detected) to reduce LLM calls and cost.
• If you want spoken translations, add a TTS step (convert translated text to audio and publish as an audio track).
• OpenAI Realtime alone cannot provide interim transcripts while the user is speaking — you need an STT stream for true in-progress translation.
Would you like a version that returns spoken translations (TTS) or one that includes simple throttling to reduce API calls?
Sources: Speech-to-text (STT) models | LiveKit Docs | OpenAI LLM plugin guide | LiveKit Docs | Models | LiveKit Docs | Realtime model plugins | LiveKit Docsstraight-greece-72452
12/06/2025, 8:51 AMtall-airline-16756
12/06/2025, 8:51 AMes)
• TTS preference: (A) use a TTS provider that returns audio bytes (I’ll show how to plug that in as a stub), or (B) synthesize speech client-side from data messages (I’ll show the frontend snippet instead)
Which TTS option do you want me to produce the final code for?straight-greece-72452
12/06/2025, 8:54 AMtall-airline-16756
12/06/2025, 8:55 AM# realtime_translator_tts.py
import os
import asyncio
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit import rtc
from livekit.plugins import deepgram, openai
load_dotenv(".env.local")
SOURCE_LANG = "it"
TARGET_LANG = "en"
DG_MODEL = "nova-2"
LLM_MODEL = "gpt-4o"
# --- Replace this stub with a real TTS provider call ---
# Should return raw PCM (16-bit little-endian) or Opus bytes plus sample rate/channels.
async def tts_synthesize_audio_bytes(text: str) -> tuple[bytes, int, int]:
"""
Stub TTS: replace with real provider that returns (audio_bytes, sample_rate, channels).
Example providers: Google TTS, Azure TTS, or any service returning PCM/Opus.
"""
# For demo, return silence 0.5s of 16kHz mono 16-bit PCM
import struct
duration_s = 0.5
sr = 16000
frames = int(sr * duration_s)
silence = b"".join(struct.pack("<h", 0) for _ in range(frames))
return silence, sr, 1
# ----------------------------------------------------
async def publish_audio_bytes_as_track(room: rtc.Room, audio_bytes: bytes, sample_rate: int, channels: int):
"""
Publish raw PCM/Opus bytes into the LiveKit room as an audio track.
The exact SDK call depends on your LiveKit Python SDK capabilities.
This function shows a conceptual flow:
1) create a local outbound track
2) push encoded frames or feed an encoder that reads audio_bytes
Replace with the appropriate LiveKit API for publishing audio from bytes.
"""
# Conceptual placeholder: SDKs often expose a LocalAudioTrack publisher or an API to push PCM frames.
# Example pseudo-code (not real SDK call):
# track = room.create_local_audio_track(sample_rate=sample_rate, channels=channels)
# track.push_pcm_frames(audio_bytes)
# await room.local_participant.publish_track(track)
# For minimal demo, we print length to indicate publishing point.
print(f"[publish_audio_bytes_as_track] publishing {len(audio_bytes)} bytes sr={sample_rate} ch={channels}")
# Insert actual publishing implementation here.
async def entrypoint(ctx: JobContext):
await ctx.connect(auto_subscribe=rtc.AutoSubscribe.AUDIO_ONLY)
stt = deepgram.STT(api_key=os.environ["DG_API_KEY"], model=DG_MODEL, interim_results=True)
llm = openai.LLM(api_key=os.environ["OPENAI_API_KEY"], model=LLM_MODEL)
async def handle_audio_track(track: rtc.RemoteTrack, participant):
if track.kind != rtc.TrackKind.KIND_AUDIO:
return
audio_stream = rtc.AudioStream(track)
async def stt_stream_processor():
async for ev in stt.stream(audio_stream, language=SOURCE_LANG):
if not ev.alternatives:
continue
text = ev.alternatives[0].text.strip()
if not text:
continue
# Translate the interim chunk into English
prompt = [
{"role": "system", "content": f"Translate the following Italian text into English. Return only the translation."},
{"role": "user", "content": text}
]
try:
resp = await llm.chat(messages=prompt)
translated = resp.choices[0].message.content.strip()
except Exception as e:
translated = "[translation_error]"
# Publish translated text as a data message (optional)
await ctx.room.local_participant.publish_data(translated, topic="translation")
# Synthesize translated speech (TTS) and publish as audio track
try:
audio_bytes, sr, ch = await tts_synthesize_audio_bytes(translated)
await publish_audio_bytes_as_track(ctx.room, audio_bytes, sr, ch)
except Exception as e:
print("TTS/publish error:", e)
asyncio.create_task(stt_stream_processor())
@ctx.room.on("track_subscribed")
async def on_track_subscribed(track, participant):
await handle_audio_track(track, participant)
while ctx.room.connection_state == rtc.ConnectionState.CONN_CONNECTED:
await asyncio.sleep(1)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
.env.local
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
LIVEKIT_URL=wss://<your-project>.livekit.cloud
OPENAI_API_KEY=your_openai_api_key
DG_API_KEY=your_deepgram_api_key
Install
• uv add "livekit-agents[openai,deepgram]~=1.2" python-dotenv
Notes and integration tips
• This is a pipeline (STT → LLM → TTS). That’s expected for spoken realtime translation.
• TTS stub: replace tts_synthesize_audio_bytes with a concrete provider call that returns PCM or Opus bytes plus sample rate/channels.
• Publishing audio: replace publish_audio_bytes_as_track with the correct LiveKit SDK method to create a local audio track and push frames (SDK behavior differs; some SDKs accept an audio source you feed PCM into, others require encoded Opus frames).
• To reduce cost and jitter, debounce interim translations (e.g., translate only if last translation was >500ms ago or if the interim text ends with punctuation).
• If you want, I can:
◦ Provide an example tts_synthesize_audio_bytes implementing Google Cloud TTS or Azure TTS (requires their credentials), and
◦ Adapt publish_audio_bytes_as_track to a specific LiveKit Python SDK method if you tell me which SDK version you use.
Which TTS provider would you like me to show a concrete implementation for (Google Cloud TTS, Azure TTS, Amazon Polly, or another)?straight-greece-72452
12/06/2025, 2:04 PMtall-airline-16756
12/06/2025, 2:04 PM.env.local and load with python-dotenv (you already use this).
▪︎ Docker: docker run -e OPENAI_API_KEY=... -e TARGET_LANG=en ... image
▪︎ Kubernetes: set env in Deployment manifest or use Secrets.
◦ Use distinct names like SOURCE_LANG=it, TARGET_LANG=en, TTS_PROVIDER=google, TRANSLATION_THROTTLE_MS=500.
• Cloud provider config / Secrets manager
◦ Store keys in AWS Secrets Manager, GCP Secret Manager, or Azure Key Vault and inject at runtime (preferred for production).
◦ Mount secrets as env vars or files for the agent process.
◦ Use IAM roles/service accounts rather than long-lived keys where possible.
• CLI flags / command-line args
◦ Accept flags in your agent entrypoint and parse with argparse. Example:
▪︎ python agent.py --target-lang en --throttle 500
◦ Combine with env vars so secrets still come from env/secret store.
• Config files (YAML/JSON)
◦ Provide non-secret config via a file (e.g., config.yaml) mounted into the container.
◦ Use a single env var like CONFIG_PATH=/etc/agent/config.yaml or load from working dir.
• LiveKit agent runtime / builder settings
◦ If you deploy using LiveKit’s agent CLI/builder, include env vars in the deploy config so the cloud runner injects them into the agent process (use secure secret fields for keys).
◦ Use the agent’s entrypoint to read env vars or flags.
How to wire these into your Python agent (minimal patterns)
1) Environment-first (recommended)
• Read env vars at startup and fall back to defaults:
import os
SOURCE_LANG = os.getenv("SOURCE_LANG", "it")
TARGET_LANG = os.getenv("TARGET_LANG", "en")
TRANSLATION_THROTTLE_MS = int(os.getenv("TRANSLATION_THROTTLE_MS", "500"))
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
DG_API_KEY = os.getenv("DG_API_KEY")
2) Command-line override
• Parse args and let them override env vars:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--target-lang")
args = parser.parse_args()
TARGET_LANG = args.target_lang or os.getenv("TARGET_LANG", "en")
3) Config file fallback
• Load YAML/JSON if present:
import yaml, os
cfg_path = os.getenv("CONFIG_PATH")
if cfg_path and os.path.exists(cfg_path):
cfg = yaml.safe_load(open(cfg_path))
TARGET_LANG = cfg.get("target_lang", TARGET_LANG)
Deployment examples
• Docker
◦ Build image from your agent code.
◦ Run with env:
docker run -e OPENAI_API_KEY=... -e DG_API_KEY=... -e TARGET_LANG=en my-agent-image
• Kubernetes (Deployment snippet)
◦ Use a Secret for API keys and reference it in the Pod env.
◦ Use ConfigMap for non-secret params (throttle, langs).
◦ Example pattern (pseudo):
env:
• name: OPENAI_API_KEY
valueFrom: secretKeyRef: { name: openai-secret, key: api_key }
• name: TARGET_LANG
value: "en"
• LiveKit agent deploy (CLI/builder)
◦ Add env vars and secret fields in the agent deployment config so the cloud runner injects them. Use secure fields for API keys and plain env vars for non-secrets.
Best practices
• Keep secrets out of code and repo; use secrets manager or Kubernetes Secrets.
• Use short-lived credentials or roles where possible.
• Default safe values in code; make behavior explicit via env/flags.
• Validate required settings at startup and fail fast if essential secrets are missing.
• For runtime tuning (throttle, voice, model), prefer non-secret env vars so you can change behavior without rebuilding images.
If you tell me your deployment target (LiveKit Cloud agent runner, Docker on VM, Kubernetes, or serverless), I’ll give the exact deployment snippet (Docker run, k8s manifest, or LiveKit agent config) and a ready-to-drop env/secret setup for your translator agent.straight-greece-72452
12/06/2025, 2:07 PMtall-airline-16756
12/06/2025, 2:07 PMimport os
SOURCE_LANG = os.getenv("SOURCE_LANG", "it")
TARGET_LANG = os.getenv("TARGET_LANG", "en")
THROTTLE_MS = int(os.getenv("TRANSLATION_THROTTLE_MS", "500"))
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
DG_API_KEY = os.getenv("DG_API_KEY")
LiveKit Cloud: adding env vars & secrets
• Secrets: create secrets in LiveKit Cloud UI (or via the LiveKit CLI) and reference them in the agent deployment as env vars.
• Plain env vars: add them directly in the agent deployment config.
Example LiveKit agent deployment snippet (YAML-style pseudoconfig for the LiveKit agent runner)
name: realtime-translator
image: your-registry/realtime-translator:latest
env:
- name: SOURCE_LANG
value: "it"
- name: TARGET_LANG
value: "en"
- name: TRANSLATION_THROTTLE_MS
value: "500"
- name: LLM_MODEL
value: "gpt-4o"
secrets:
- name: OPENAI_API_KEY # LiveKit Cloud will inject this as an env var
- name: DG_API_KEY
Notes:
• The LiveKit Cloud UI or CLI will map those secret names to env vars inside the container (OPENAI_API_KEY, DG_API_KEY).
• If using LiveKit CLI builder, there is a settings section to add env vars and secure secrets — place keys there.
Command-line / flag override (optional)
• Accept flags in your agent process and let them override env vars:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--target-lang")
args = parser.parse_args()
TARGET_LANG = args.target_lang or os.getenv("TARGET_LANG", "en")
• Pass flags in the agent runner command if LiveKit Cloud supports custom command args for the container entrypoint.
Example: updating throttle at runtime
• Set TRANSLATION_THROTTLE_MS as an env var and change it in LiveKit Cloud to adjust behavior without redeploying.
Best practices
• Keep secrets in LiveKit Cloud secret fields, not in plain env vars or repo.
• Use non-secret env vars for tunables so you can change behavior without rebuilding images.
• Validate required env vars on startup and fail fast with clear logs.
• Use reasonable defaults (e.g., 500ms throttle) and allow overrides.
• For credentials, prefer short-lived or rotated keys if supported.
If you want, I can:
• Provide the exact LiveKit CLI commands or UI steps to create and inject secrets into an agent deployment, or
• Produce a ready-to-deploy example agent manifest compatible with the LiveKit Cloud agent runner (tell me whether you use the LiveKit UI or CLI). Which would you like?straight-greece-72452
12/06/2025, 2:09 PMtall-airline-16756
12/06/2025, 2:09 PM// send a control message (topic "agent.control")
room.localParticipant.publishData(
JSON.stringify({ action: "set_params", params: { target_lang: "en", throttle_ms: 300 } }),
"agent.control"
);
• Agent (Python) — subscribe to dataReceived and apply changes:
@ctx.room.on("data_received")
async def on_data(data, participant, topic):
if topic != "agent.control":
return
msg = data.decode() # bytes -> str
payload = json.loads(msg)
if payload.get("action") == "set_params":
params = payload.get("params", {})
TARGET_LANG = params.get("target_lang", TARGET_LANG)
THROTTLE_MS = int(params.get("throttle_ms", THROTTLE_MS))
# apply immediately (thread-safe update if needed)
Notes: data messages are low-latency and included in LiveKit room traffic. Use for per-user or global room settings.
2) Room/Participant metadata in join token (good for settings at connect time)
• When to use: parameters known at join time (preferred for per-participant configuration) and when you want to authenticate/authorize those params.
• Client: request a token from your app server that embeds metadata (example param field). Your server issues LiveKit token with metadata.
• Agent (Python): read participant metadata when participant joins:
@ctx.room.on("participant_joined")
async def on_participant_joined(participant):
md = participant.metadata # string set at token creation
# parse JSON metadata like {"target_lang":"en"}
Notes: safer for pre-approved params; cannot be changed without reconnect.
3) Dedicated HTTP control endpoint on your server (useful when you need auth/rate limits)
• When to use: complex authorization, audit logging, persistent per-user prefs, or if you prefer REST for control.
• Flow: client calls your backend API (e.g., POST /agent/config) with params → your backend validates and writes to a store (Redis/DB) or pushes to agent via LiveKit data message or server-side event.
• Example: backend publishes to agent with LiveKit data API or via LiveKit Room REST publish (or agent subscribes to pub/sub channel).
Benefits: centralized auth, audit, and can target specific agent instances.
4) LiveKit Server-side REST publish (server→room) or Signal channels (if available)
• When to use: your backend needs to push a change to agents without client involvement. Use LiveKit REST API to publish data messages into a room which the agent receives.
5) Token-scoped request headers or query params (less common)
• When to use: initial bootstrapping via a separate control HTTP request to the agent when the agent exposes a control URL (only if you run a control endpoint).
• Not recommended to put secrets here.
Implementation tips and best practices
• Authorization: always validate client requests. If you accept client-sent params, ensure the client is allowed to change them (check participant ID / token / role).
• Atomic updates / concurrency: use thread-safe/shared state (asyncio locks or an actor) when agent code reads/writes config used by streaming loops.
• Per-participant vs global: decide if params apply to one participant or whole room. Include participant identity in control messages if per-participant.
• Rate-limiting & throttling: reject too-frequent updates. Use TRANSLATION_THROTTLE_MS or server-side rate limits.
• Validation & defaults: validate values (language codes, model names) and fall back to defaults. Log invalid attempts.
• Persistence: store user prefs in DB if they should persist between sessions.
• Security: never accept raw API keys from client. Secrets must remain server-side.
Concrete example: client → agent via backend control (recommended pattern)
1. Client POST /set-agent-params { room: "r1", target_lang: "en" } → your backend
2. Backend validates + calls LiveKit REST to publish data into the room:
◦ Publish data message topic "agent.control" with params
1. Agent receives the "agent.control" data message and updates runtime config.
Python agent example (combined, thread-safe)
import asyncio, json
from asyncio import Lock
lock = Lock()
runtime = {"target_lang":"en","throttle_ms":500}
@ctx.room.on("data_received")
async def on_data(data, participant, topic):
if topic != "agent.control": return
payload = json.loads(data.decode())
if payload.get("action") != "set_params": return
async with lock:
for k,v in payload.get("params",{}).items():
if k == "target_lang":
runtime["target_lang"]=v
if k == "throttle_ms":
runtime["throttle_ms"]=int(v)
# downstream processing reads runtime dict under lock or copy it
When your STT→LLM loop runs, read a local snapshot:
async with lock:
current = runtime.copy()
# use current["target_lang"] etc.
Which approach should you use?
• If you need quick, low-latency changes from the client while in the room: use data messages.
• If params must be enforced at join and authenticated: embed in token metadata.
• If you need centralized auth/audit or changing parameters from outside the room: use your backend + LiveKit REST publish.
Tell me which pattern you prefer (data messages, token metadata, or backend control), and I’ll produce:
• exact client code (React/JS) for sending updates,
• the backend snippet to validate + publish via LiveKit REST (if you choose backend control),
• and a ready-to-run Python agent snippet that safely applies and uses the params in streaming translation/TTS.straight-greece-72452
12/06/2025, 2:12 PMtall-airline-16756
12/06/2025, 2:13 PMstraight-greece-72452
12/06/2025, 2:15 PMtall-airline-16756
12/06/2025, 2:15 PM// server/token.ts (Node.js/Express)
import express from "express";
import { AccessToken } from "livekit-server-sdk";
const app = express();
app.use(express.json());
app.post("/token", (req, res) => {
const { identity, room } = req.body;
const apiKey = process.env.LIVEKIT_API_KEY!;
const apiSecret = process.env.LIVEKIT_API_SECRET!;
const at = new AccessToken(apiKey, apiSecret, { identity });
at.addGrant({ roomJoin: true, room, canPublish: true, canSubscribe: true });
const token = at.toJwt();
res.json({ token });
});
app.listen(3000);
• Client requests POST /token with identity and room to receive a JWT.
2) Install LiveKit client SDK in Angular
• npm install livekit-client
3) Angular service: connect, publish mic, handle data messages
// src/app/services/livekit.service.ts
import { Injectable } from "@angular/core";
import { Room, RemoteParticipant, RoomEvent } from "livekit-client";
import { HttpClient } from "@angular/common/http";
@Injectable({ providedIn: "root" })
export class LivekitService {
room = new Room();
constructor(private http: HttpClient) {}
async getToken(identity: string, roomName: string) {
const resp = await this.http.post<{ token: string }>("/token", { identity, room: roomName }).toPromise();
return resp.token;
}
async connect(identity: string, roomName: string) {
const token = await this.getToken(identity, roomName);
await this.room.connect("wss://<your-project>.livekit.cloud", token);
// enable mic
await this.room.localParticipant.setMicrophoneEnabled(true);
// handle data messages from agent (translations)
this.room.on(RoomEvent.DataReceived, (payload, participant, topic) => {
if (topic === "translation") {
const text = new TextDecoder().decode(payload);
window.dispatchEvent(new CustomEvent("translation", { detail: { text, from: participant.identity } }));
}
if (topic === "agent.control") {
// handle other control topics
}
});
// detect agent participant join (optional)
this.room.on(RoomEvent.ParticipantConnected, (p: RemoteParticipant) => {
console.log("participant joined", p.identity);
});
}
// send control params to agent (data message)
sendAgentControl(params: any) {
const payload = JSON.stringify({ action: "set_params", params });
this.room.localParticipant.publishData(payload, "agent.control");
}
}
4) Angular component: UI to connect, show translations, change params
// src/app/components/translator/translator.component.ts
import { Component, OnInit } from "@angular/core";
import { LivekitService } from "../../services/livekit.service";
@Component({
selector: "app-translator",
template: `
<button (click)="connect()">Connect</button>
<div>
<label>Target Lang: <input [(ngModel)]="targetLang" /></label>
<button (click)="setParams()">Set Params</button>
</div>
<div *ngFor="let msg of translations">{{ msg }}</div>
`
})
export class TranslatorComponent implements OnInit {
translations: string[] = [];
targetLang = "en";
constructor(private lk: LivekitService) {}
ngOnInit() {
window.addEventListener("translation", (e: any) => {
this.translations.push(e.detail.text);
});
}
async connect() {
await this.lk.connect(`user-${Math.random().toString(36).slice(2)}`, "translator-room");
}
setParams() {
this.lk.sendAgentControl({ target_lang: this.targetLang, throttle_ms: 500 });
}
}
• Remember to import FormsModule and HttpClientModule in your AppModule.
5) How the agent receives params and responds
• Use data messages with topic "agent.control" (shown earlier). The server-side agent subscribes to dataReceived and updates runtime config. The agent publishes translated text as data messages with topic "translation" and publishes TTS audio as an audio track into the same room.
6) Publishing/receiving audio
• Your Angular client publishes its microphone via setMicrophoneEnabled(true).
• Agent publishes audio track (TTS) into the room; the browser auto-subscribes and will receive / play it. No extra handling required other than subscribing UI if you want playback controls.
7) LiveKit Room permissions and security
• Generate tokens on a trusted backend only. Do not embed API secrets in the client.
• If clients can request param changes, validate on backend or authorize by participant identity.
8) Optional: request-based control via backend
• Instead of client→room data message, client POSTs to your backend; backend validates and uses LiveKit REST API to publish a data message into the room targeting the agent. This is useful if you need audit, auth, or to avoid exposing a direct control channel.
9) Summary flow
• Client requests token -> connects to LiveKit room -> publishes mic -> sends control params via data message -> agent receives audio, translates, publishes translated text (data) and TTS audio -> client displays text and plays audio (subscribed track).
If you want, I can:
• Provide a finished Angular project skeleton (package.json, AppModule, component files).
• Show exact Room URL and RoomEvent enums for the livekit-client version you’re using.
Which of those would you like next?