polite-dog-12152
12/10/2025, 6:16 AMtall-airline-16756
12/10/2025, 6:16 AMtall-airline-16756
12/10/2025, 6:16 AMpolite-dog-12152
12/10/2025, 6:18 AMtall-airline-16756
12/10/2025, 6:19 AMfrom livekit.plugins import openai
from livekit.plugins.agents import AgentSession
session = AgentSession(
llm=openai.LLM(
model="gpt-4o-mini",
temperature=0.8,
tool_choice="auto",
# base_url="https://custom-api.example", api_key="KEY" # optional
),
# ... tts, stt, vad, etc.
)
TypeScript example
import * as openai from '@livekit/agents-plugin-openai';
import { AgentSession } from '@livekit/agents';
const session = new AgentSession({
llm: openai.LLM({
model: "gpt-4o-mini",
temperature: 0.8,
tool_choice: "auto",
// base_url: "https://custom-api.example", api_key: "KEY" // optional
}),
// ... tts, stt, vad, etc.
});
Would you like examples for different temperature values, forcing tools with tool_choice: "required", or help wiring `base_url`/`api_key` for a custom provider?
Sources: OpenAI LLM plugin guide | LiveKit Docs | Models | LiveKit Docspolite-dog-12152
12/10/2025, 6:22 AMtall-airline-16756
12/10/2025, 6:22 AMextra_kwargs / modelOptions or the plugin-specific LLM constructors.
• Use NotGiven when you want defaults; set explicit values to override behavior.
Python examples
1) Using the OpenAI plugin LLM with extra options:
from livekit.plugins import openai
from livekit.plugins.agents import AgentSession
session = AgentSession(
llm=openai.LLM(
model="gpt-4o-mini",
temperature=0.8,
tool_choice="auto",
# provider-specific/advanced options:
max_completion_tokens=300,
reasoning_effort="medium",
verbosity="normal",
_strict_tool_schema=True,
metadata={"user_id":"1234"},
store=True,
# timeout and provider formatting typically passed via extra args:
extra_kwargs={
"timeout": None,
"_provider_fmt": "default"
}
),
)
2) Using LiveKit Inference inference.LLM with modelOptions:
from livekit.agents import AgentSession, inference
session = AgentSession(
llm=inference.LLM(
model="openai/gpt-5-mini",
provider="openai",
extra_kwargs={
"max_completion_tokens": 300,
"reasoning_effort": "low",
"service_tier": "standard",
"metadata": {"session":"signup"},
"store": False
}
)
)
TypeScript examples
1) OpenAI plugin:
import * as openai from '@livekit/agents-plugin-openai';
import { AgentSession } from '@livekit/agents';
const session = new AgentSession({
llm: openai.LLM({
model: "gpt-4o-mini",
temperature: 0.8,
tool_choice: "auto",
max_completion_tokens: 300,
reasoning_effort: "medium",
verbosity: "normal",
_strict_tool_schema: true,
metadata: { user_id: "1234" },
store: true,
extra_kwargs: { _provider_fmt: "default", timeout: null }
})
});
2) LiveKit Inference:
import { AgentSession, inference } from '@livekit/agents';
const session = new AgentSession({
llm: new inference.LLM({
model: "openai/gpt-5-mini",
provider: "openai",
modelOptions: {
max_completion_tokens: 300,
reasoning_effort: "low",
service_tier: "standard",
metadata: { session: "signup" },
store: false
}
})
});
Would you like concrete examples for specific values (e.g., forcing tool_choice: "required", different reasoning_effort settings, or Realtime voice settings)?
Sources: OpenAI LLM models | LiveKit Docs | OpenAI LLM plugin guide | LiveKit Docs | OpenAI Realtime API plugin guide | LiveKit docs | Large language models (LLM) | LiveKit Docs | OpenAI and LiveKit | LiveKit docspolite-dog-12152
12/10/2025, 6:27 AMtall-airline-16756
12/10/2025, 6:28 AMinstructions (system prompt) — simplest, most effective
• Add emotional guidance to the LLM system prompt and to TTS instructions for consistent text + speech tone.
• Example (Python):
llm=openai.LLM(
model="gpt-4o-mini",
instructions="You are warm, empathetic, and concise. Show excitement for good news and gentle concern for problems."
)
tts=openai.TTS(
model="gpt-4o-mini-tts",
voice="alloy",
instructions="Speak warmly and expressively; emphasize empathy when the user is upset."
)
2) Structured output with emotion metadata — best for programmatic control
• Have the LLM return JSON like {"response":"...", "emotion":"happy"} so your agent routes emotion to TTS or UI.
• Example flow:
◦ LLM returns JSON with voice_instructions and response.
◦ Your TTS node reads voice_instructions and sets TTS `instructions`/voice parameters, then speaks response.
3) Tune temperature for expressive language
• Increase temperature (e.g., 0.7–1.2) for more creative, varied phrasing; lower for neutral/deterministic replies.
• Example:
openai.LLM(model="gpt-4o-mini", temperature=0.9)
4) Use Realtime TTS models for expressive speech (low-latency)
• Realtime models support voice selection and expressive instructions (useful for voice agents).
• Example:
openai.realtime.RealtimeModel(voice="marin", instructions="Be enthusiastic and friendly.")
5) Combine methods for best results
• Use instructions to set overall persona, structured output for explicit emotion signals, temperature for creativity, and expressive TTS (Realtime or OpenAI TTS) to realize emotion in audio.
If you want, I can:
• Produce a full code example implementing structured JSON output + TTS handling, or
• Show how to prompt-engineer a set of instructions for specific emotions (happy, sympathetic, urgent). Which would you prefer? Sources: OpenAI TTS plugin guide | LiveKit docs | Tool definition and use | LiveKit docs | OpenAI LLM plugin guide | LiveKit Docs | OpenAI Realtime API plugin guide | LiveKit docspolite-dog-12152
12/10/2025, 6:31 AMtall-airline-16756
12/10/2025, 6:31 AMpolite-dog-12152
12/10/2025, 6:32 AMtall-airline-16756
12/10/2025, 6:32 AMfrom livekit.plugins import elevenlabs, openai
from livekit.plugins.agents import AgentSession
# Configure an OpenAI LLM (instructions guide tone/emotion)
llm = openai.LLM(
model="gpt-4o-mini",
temperature=0.8,
instructions="You are warm and empathetic. Keep replies friendly and concise."
)
# Configure ElevenLabs TTS
tts = elevenlabs.TTS(
voice_id="ODq5zmih8GrVes37Dizd", # replace with your ElevenLabs voice id
model="eleven_multilingual_v2",
# optional ElevenLabs-specific settings:
stability=0.6, # 0.0-1.0, lower = more varied
similarity_boost=0.7 # 0.0-1.0, higher = closer to voice sample
)
# Create the AgentSession with LLM + TTS
session = AgentSession(
llm=llm,
tts=tts,
# add stt, vad, tools, etc. as needed
)
# Example: generate a text response from LLM and synthesize it via ElevenLabs TTS
async def run_example():
# use session API to ask the agent; exact call depends on your agent flow
# this pattern shows conceptually: get text from LLM, then synthesize via TTS
response = await session.generate_text("Hello! How can I help you today?")
text = response.text # agent's text reply
# synthesize speech (this method name may vary by SDK; adapt if needed)
audio_bytes = await session.tts.synthesize(text)
# write to file for playback
with open("response.wav", "wb") as f:
f.write(audio_bytes)
# Run in an async event loop in your application
# e.g., asyncio.run(run_example())
Notes and tips
• Use instructions on both LLM and TTS to align emotional tone (LLM guides wording; TTS guides prosody).
• For fine-grained control, have the LLM emit JSON with an emotion field, then map that to TTS settings (stability, SSML, voice selection).
• Replace voice_id with a valid ElevenLabs voice ID from your ElevenLabs account.
• If you prefer LiveKit Inference instead of managing API keys, you can use the inference path and provide model IDs like openai/gpt-5-mini.
Would you like a full working example that:
• Shows how to parse structured JSON output from the LLM to map emotions to TTS parameters, or
• Demonstrates SSML usage with ElevenLabs for emotional emphasis?polite-dog-12152
12/10/2025, 6:36 AMtall-airline-16756
12/10/2025, 6:36 AMeleven_flash_v2_5. Example values: eleven_multilingual_v2, eleven_turbo_v2_5.
• voice_id (str) — Voice identifier. Example: "21m00Tcm4TlvDq8ikWAM".
• voice_settings (object) — Fine-tune voice behavior:
◦ stability (float, 0–1) — Consistency vs variation (lower = more variation).
◦ similarity_boost (float, 0–1) — How closely to match a reference voice.
◦ style (float, 0–1) — Expressiveness/style intensity.
◦ use_speaker_boost (bool) — Enhance clarity/distinctiveness.
◦ speed (float, >=0.5) — Speaking rate (e.g., 0.8 slower, 1.2 faster).
• language (str) — ISO-639-1 language code (e.g., en, es, fr).
• streaming_latency (int) — Latency tuning for streaming: 1 (lowest, less quality) to higher numbers (more buffering). Default ~3.
• enable_ssml_parsing (bool) — Allow SSML tags in input for prosody/pronunciation control.
• chunk_length_schedule (list[int]) — How text is chunked for streaming (default [80,120,200,260]). Values between ~50–500.
• stability, similarity_boost, style, speed (also accessible directly or inside voice_settings) — shorthand control fields if supported by SDK.
• use_tts_aligned_transcript (bool) — Enable word-level timing alignment for frontend sync (LiveKit feature tied to ElevenLabs).
• additional provider options (provider-specific flags) — e.g., low-level ElevenLabs knobs exposed via plugin (passed as extra args).
Python examples
1) Minimal setup (basic model + voice)
from livekit.plugins import elevenlabs
from livekit.plugins.agents import AgentSession
tts = elevenlabs.TTS(
model="eleven_multilingual_v2",
voice_id="21m00Tcm4TlvDq8ikWAM"
)
session = AgentSession(tts=tts)
2) Full voice_settings example
tts = elevenlabs.TTS(
model="eleven_turbo_v2_5",
voice_id="21m00Tcm4TlvDq8ikWAM",
voice_settings=elevenlabs.VoiceSettings(
stability=0.7,
similarity_boost=0.85,
style=0.6,
use_speaker_boost=True,
speed=1.05
)
)
3) Enable SSML and streaming tuning
tts = elevenlabs.TTS(
model="eleven_flash_v2_5",
voice_id="21m00Tcm4TlvDq8ikWAM",
enable_ssml_parsing=True,
streaming_latency=2,
chunk_length_schedule=[70, 110, 180, 230]
)
4) Use language + enable TTS-aligned transcript
session = AgentSession(
tts=elevenlabs.TTS(
model="eleven_multilingual_v2",
voice_id="21m00Tcm4TlvDq8ikWAM",
language="fr"
),
# top-level LiveKit flag to enable word-level timing
use_tts_aligned_transcript=True
)
5) Map emotion to TTS settings (pattern)
• Have the LLM return structured JSON: {"response":"...", "emotion":"happy"}.
• Map emotion to voice_settings (e.g., happy -> style=0.8, speed=1.1; sad -> style=0.3, speed=0.9).
• Update TTS params before synthesizing.
Notes
• Replace voice_id with a valid ElevenLabs voice from your account.
• Defaults and parameter names can vary slightly between LiveKit Python and Node SDKs; voice_settings may be nested under voice in some client constructors.
• Use enable_ssml_parsing for fine prosody control but test tags for compatibility.
Would you like:
• A TypeScript equivalent of these examples?
• A full runnable Python sample that implements emotion mapping + LLM -> ElevenLabs TTS synthesis? Sources: ElevenLabs TTS plugin guide | LiveKit Docs | Text and transcriptions | LiveKit docs | ElevenLabs TTS | LiveKit Docspolite-dog-12152
12/10/2025, 6:50 AMtall-airline-16756
12/10/2025, 6:50 AMvoice_settings (style, speed, stability, similarity_boost)
• Update TTS params and synthesize audio
Adjust voice IDs, model names, and API keys for your environment.
Prereqs
1. Install: uv add "livekit-agents[elevenlabs,openai]~=1.2"
2. .env:
• OPENAI_API_KEY=your_openai_key
• ELEVEN_API_KEY=your_eleven_key
Example code
import json
import asyncio
from livekit.plugins import openai, elevenlabs
from livekit.plugins.agents import AgentSession
# Helper: map emotion -> ElevenLabs voice settings
def emotion_to_voice_settings(emotion: str):
mapping = {
"happy": {"style": 0.8, "speed": 1.1, "stability": 0.6, "similarity_boost": 0.7},
"excited": {"style": 0.9, "speed": 1.2, "stability": 0.55, "similarity_boost": 0.6},
"neutral": {"style": 0.5, "speed": 1.0, "stability": 0.8, "similarity_boost": 0.8},
"sad": {"style": 0.3, "speed": 0.9, "stability": 0.85, "similarity_boost": 0.7},
"angry": {"style": 0.7, "speed": 1.05, "stability": 0.6, "similarity_boost": 0.65}
}
return mapping.get(emotion.lower(), mapping["neutral"])
# Setup LLM to emit structured JSON (use instructions to enforce format)
llm = openai.LLM(
model="gpt-4o-mini",
temperature=0.7,
instructions=(
"You are an assistant that must respond with JSON only. "
"Return an object with keys: 'response' (string) and 'emotion' (one-word label). "
"Example: {\"response\":\"Hello!\",\"emotion\":\"happy\"}."
)
)
# Create a default TTS config (voice_id must be valid for your ElevenLabs account)
DEFAULT_VOICE_ID = "21m00Tcm4TlvDq8ikWAM"
# Initialize AgentSession with placeholder TTS (we'll update settings dynamically)
tts = elevenlabs.TTS(
voice_id=DEFAULT_VOICE_ID,
model="eleven_multilingual_v2",
# default voice_settings; will be overridden per-emotion
voice_settings=elevenlabs.VoiceSettings(
stability=0.8,
similarity_boost=0.8,
style=0.5,
use_speaker_boost=True,
speed=1.0
),
enable_ssml_parsing=False
)
session = AgentSession(llm=llm, tts=tts)
# Function to get structured JSON from LLM
async def get_structured_response(prompt: str) -> dict:
# Use the session's LLM to generate text. API shape may vary; adapt if needed.
resp = await session.llm.generate(prompt) # returns an object with text attribute
text = resp.text if hasattr(resp, "text") else resp # adapt to SDK response shape
# Parse JSON safely
try:
parsed = json.loads(text.strip())
except Exception:
# If model returns non-JSON, try to recover by extracting JSON substring
start = text.find("{")
end = text.rfind("}") + 1
parsed = json.loads(text[start:end])
return parsed
# Function to synthesize speech with emotion-specific settings
async def synthesize_with_emotion(text: str, emotion: str, out_path: str):
settings = emotion_to_voice_settings(emotion)
# Update session.tts voice_settings dynamically before synthesizing.
# Some SDKs accept voice_settings directly; others require constructing a new TTS instance.
# Here we update the existing TTS object's settings if supported.
session.tts.voice_settings = elevenlabs.VoiceSettings(
stability=settings["stability"],
similarity_boost=settings["similarity_boost"],
style=settings["style"],
use_speaker_boost=True,
speed=settings["speed"]
)
# Synthesize audio bytes
audio_bytes = await session.tts.synthesize(text) # returns bytes (wav/pcm)
with open(out_path, "wb") as f:
f.write(audio_bytes)
async def main():
user_prompt = "User: I just got promoted at work! Respond encouragingly."
structured = await get_structured_response(user_prompt)
response_text = structured.get("response", "Congratulations!")
emotion_label = structured.get("emotion", "happy")
outfile = "response.wav"
await synthesize_with_emotion(response_text, emotion_label, outfile)
print(f"Synthesized '{emotion_label}' speech to {outfile}")
if __name__ == "__main__":
asyncio.run(main())
Notes and tips
• The exact method names for generating text (session.llm.generate) and TTS synthesis (session.tts.synthesize) may vary by SDK version; adapt to your installed LiveKit package if necessary.
• Use strong, constrained instructions to make the LLM return valid JSON reliably. You can add "If you cannot comply, return {\"response\":\"...\",\"emotion\":\"neutral\"}" to avoid parse errors.
• For production, validate and sanitize the LLM output before using it.
• You can alternatively have the LLM return an SSML response and pass that to ElevenLabs with enable_ssml_parsing=True for more precise prosody control.
• Replace DEFAULT_VOICE_ID with a voice ID from your ElevenLabs account.
Would you like a version that:
• Builds the TTS call by creating a new elevenlabs.TTS(...) per request instead of mutating session.tts, or
• Includes SSML examples for emotion-specific prosody?polite-dog-12152
12/10/2025, 9:19 AMtall-airline-16756
12/10/2025, 9:19 AMaws.STT directly with a SpeechStream like in your snippet. Use aws.STT inside an AgentSession, or create a streaming instance with stt.stream() and push audio frames. Below are concise correct examples and the key parameters.
1) AgentSession (recommended simple usage)
from livekit.agents import AgentSession
from livekit.plugins import aws, openai, elevenlabs
session = AgentSession(
stt=aws.STT(language="en-US", number_of_channels=1),
llm=openai.LLM(model="gpt-4o-mini", instructions="Be concise and friendly."),
tts=elevenlabs.TTS(voice_id="21m00Tcm4TlvDq8ikWAM", model="eleven_multilingual_v2")
)
2) Streaming STT (push audio frames manually)
import asyncio
from livekit import rtc
from livekit.plugins import aws
async def process_audio_track(track: rtc.RemoteAudioTrack):
stt = aws.STT(language="en-US", number_of_channels=1)
stt_stream = stt.stream() # streaming instance
audio_stream = rtc.AudioStream(track)
async for audio_event in audio_stream:
stt_stream.push_frame(audio_event.frame)
await stt_stream.aclose()
3) Key aws.STT parameters
• language (str) — e.g., "en-US"
• number_of_channels (int) — e.g., 1
• vocabulary_name (str) — custom vocabulary name
• vocab_filter_name / vocab_filter_method — sensitive-word filtering
• session_id (str) — optional session identifier
• speech_region (str) — AWS Transcribe region
4) Example: combine STT → structured LLM → emotion-mapped ElevenLabs TTS
• STT transcribes audio to text.
• Send text to LLM with instructions to return JSON: {"response":"...", "emotion":"happy"}.
• Map emotion → ElevenLabs voice_settings and synthesize (see earlier emotion-to-voice_settings example).
If you want, I can:
• Provide a full runnable example wiring a WebRTC audio track -> AWS STT -> LLM -> ElevenLabs TTS, or
• Show how to add custom vocabulary and region settings to aws.STT. Which do you prefer? Sources: Amazon Transcribe plugin guide | LiveKit Docs | AWS AI and LiveKit | LiveKit Docs | Text and transcriptions | LiveKit docspolite-dog-12152
12/10/2025, 9:29 AMtall-airline-16756
12/10/2025, 9:29 AMnumber_of_channels without enabling channel identification. Enable channel identification when using multi-channel audio.
Quick fix — set enable_channel_identification=True (and match number_of_channels) when creating the AWS STT instance. Example:
from livekit.plugins import aws
from livekit.agents import AgentSession
session = AgentSession(
stt=aws.STT(
language="en-US",
number_of_channels=2, # e.g., stereo or multi-channel input
enable_channel_identification=True, # required when number_of_channels > 1
),
# llm, tts, etc.
)
Checks to confirm:
• Use the correct number_of_channels (e.g., 2 for stereo).
• AWS credentials and AWS_DEFAULT_REGION are set.
• If you stream audio manually, ensure frames preserve channel layout.
If you still see the error, tell me:
• the exact number_of_channels you set,
• whether you’re using AgentSession or manual streaming,
• and a short snippet of the STT initialization you’re using — I’ll help adjust it. Sources: Amazon Transcribe plugin guide | LiveKit Docspolite-dog-12152
12/10/2025, 9:35 AMtall-airline-16756
12/10/2025, 9:35 AMnum_channels on rtc.AudioSource and number_of_channels on aws.STT?
• Are you using AgentSession(..., stt=aws.STT(...)) or a manual stt.stream() flow?
Answer those and I’ll provide the exact code changes to fix it.polite-dog-12152
12/10/2025, 9:36 AMtall-airline-16756
12/10/2025, 9:36 AMnumber_of_channels you set (rtc.AudioSource num_channels and aws.STT number_of_channels).
2. sample_rate (you used 24000 in code — confirm).
3. Whether input is SIP (phone) or WebRTC mic.
4. Any error messages or a short example of the transcript you received (or “no transcript”).
Give those and I’ll provide exact code/config changes to fix the audio path and improve recognition (channel ID, sample rate, VAD, or TTS settings as needed).polite-dog-12152
12/10/2025, 9:37 AMtall-airline-16756
12/10/2025, 9:37 AM"en-US")
2. Is the audio source SIP (phone) or WebRTC mic?
3. Confirm these values from your running setup:
◦ rtc.AudioSource sample_rate (you showed 24000)
◦ rtc.AudioSource num_channels (you showed 1)
◦ aws.STT number_of_channels and any channel-identification setting
1. Do you get any transcript text at all? If yes, paste one short example of what the system produced and what you actually said (e.g., you said "hello" → got "oh").
Common fixes I’ll apply once you confirm:
• If SIP/phone: set sample_rate=8000 or 16000 and number_of_channels to match phone channel count; enable enable_channel_identification=True when channels>1.
• If WebRTC mic: 16000 or 24000 is fine, but keep same sample_rate in both AudioSource and STT.
• Enable noise_cancellation (you already use BVCTelephony — I’ll suggest VAD/min_silence tweaks).
• Use language="en-US" and provide simple prompts to LLM if transcript errors are interpretation issues.
• If transcripts are short/garbled, lower VAD min_silence_duration or increase STT streaming buffering (streaming_latency) for better frames.
Reply with answers to 1–4 and I’ll give the exact code snippet to change in your script.polite-dog-12152
12/10/2025, 9:45 AMtall-airline-16756
12/10/2025, 9:45 AMfrom livekit import rtc
from livekit.plugins import aws
# Match sample_rate and num_channels with your audio source
audio_source = rtc.AudioSource(sample_rate=16000, num_channels=1)
stt = aws.STT(language="en-US", number_of_channels=1)
stt_stream = stt.stream() # streaming instance for low-latency transcription
async def process_track(track: rtc.RemoteAudioTrack):
audio_stream = rtc.AudioStream(track)
async for audio_event in audio_stream:
# push raw frames continuously; STT returns interim results quickly
stt_stream.push_frame(audio_event.frame)
await stt_stream.aclose()
Tuning knobs to try (start here)
• sample_rate: try 16000 for telephony or 24000 for higher-quality mics. Keep it consistent.
• VAD min_silence_duration: 0.15–0.25s for faster detection.
• chunk sizes / streaming_latency: lower values for faster but less stable output.
• If you need final accuracy later, accept interim partials then replace with final transcript when available.
If you want, tell me:
• current sample_rate and number_of_channels, and
• whether you’re using AgentSession STT or manual stt.stream() — I’ll give exact patched code for your setup.polite-dog-12152
12/11/2025, 5:19 AMtall-airline-16756
12/11/2025, 5:19 AMpolite-dog-12152
12/11/2025, 5:20 AMtall-airline-16756
12/11/2025, 5:20 AMAgentSession (session.start with stt=aws.STT(...)) or do you push frames manually with stt.stream()?polite-dog-12152
12/11/2025, 5:20 AMtall-airline-16756
12/11/2025, 5:21 AMimport time
import statistics
from collections import deque
class LatencyRecorder:
def __init__(self, max_samples=1000):
self.samples = deque(maxlen=max_samples) # store per-request dicts
def new_request(self, req_id):
return {
"id": req_id,
"ts": {"start": time.time()}
}
def mark(self, req, name):
req["ts"][name] = time.time()
def finalize(self, req):
# compute deltas for segments you care about
ts = req["ts"]
result = {
"id": req["id"],
"total": ts.get("playback_end", ts.get("tts_end", ts.get("llm_end", time.time()))) - ts["start"],
"capture_to_stt_send": ts.get("stt_send", ts["start"]) - ts["start"],
"stt_send_to_stt_recv": ts.get("stt_recv", ts.get("stt_final", ts.get("stt_partial", ts.get("stt_recv", time.time())))) - ts.get("stt_send", ts["start"]),
"stt_recv_to_llm_send": ts.get("llm_send", ts.get("stt_recv", ts.get("stt_final", time.time()))) - ts.get("stt_recv", ts.get("stt_final", time.time())),
"llm_send_to_llm_recv": ts.get("llm_recv", ts.get("llm_end", time.time())) - ts.get("llm_send", ts.get("stt_recv", time.time())),
"llm_recv_to_tts_send": ts.get("tts_send", ts.get("llm_recv", time.time())) - ts.get("llm_recv", time.time()),
"tts_send_to_tts_end": ts.get("tts_end", time.time()) - ts.get("tts_send", time.time()),
"tts_end_to_playback_end": ts.get("playback_end", ts.get("tts_end", time.time())) - ts.get("tts_end", time.time())
}
self.samples.append(result)
return result
def summary(self):
if not self.samples:
return {}
def agg(field):
vals = [s[field] for s in self.samples if s.get(field) is not None]
if not vals: return {}
return {
"count": len(vals),
"mean": statistics.mean(vals),
"p50": statistics.median(vals),
"p95": statistics.quantiles(vals, n=100)[94]
}
keys = ["total","capture_to_stt_send","stt_send_to_stt_recv","stt_recv_to_llm_send","llm_send_to_llm_recv","llm_recv_to_tts_send","tts_send_to_tts_end","tts_end_to_playback_end"]
return {k: agg(k) for k in keys}
2) Where to add marks in your agent flow
• At audio capture (right before you push frame / hand to STT): mark "stt_send".
• On receiving STT interim result: mark "stt_partial" (optional).
• On receiving STT final transcript: mark "stt_final" or "stt_recv".
• Right before calling LLM: mark "llm_send".
• Immediately after LLM returns final text: mark "llm_recv".
• Right before sending text to TTS synth: mark "tts_send".
• After TTS returns audio bytes: mark "tts_end".
• After you publish/playback the TTS track (or after you write file/playback finished): mark "playback_end".
3) Example integration snippets (place into your script)
• Create recorder and start request:
rec = LatencyRecorder()
req = rec.new_request(req_id=str(uuid.uuid4()))
# capture happens; when ready to send to STT:
rec.mark(req, "stt_send")
# push frame to stt.stream() or let AgentSession handle it
• On STT interim / final callbacks (example placeholders):
# interim result handler
rec.mark(req, "stt_partial")
# final transcript handler (when you have final text)
rec.mark(req, "stt_final") # or "stt_recv"
# now send to LLM
rec.mark(req, "llm_send")
llm_text = await session.llm.generate(transcript_text) # adapt call
rec.mark(req, "llm_recv")
• Before/after TTS:
rec.mark(req, "tts_send")
audio_bytes = await session.tts.synthesize(llm_text) # adapt call
rec.mark(req, "tts_end")
# publish/playback audio (async)
await publish_audio_bytes(audio_bytes) # your existing playback method
rec.mark(req, "playback_end")
• Finalize and log one request:
result = rec.finalize(req)
print("latency_breakdown:", result)
print("running_summary:", rec.summary())
4) Tips for accurate measurement
• Use monotonic clocks (time.time() is OK for simple; use time.perf_counter() if you want monotonic high-res).
• Include both interim STT timestamps and final STT — interim helps see streaming responsiveness vs final accuracy delays.
• Instrument network boundaries separately if possible (e.g., timestamp before HTTP/gRPC call and at response receipt).
• For LLM/TTS remote calls, record both request size and response size; large responses increase serialization time.
• Run with realistic load and collect p50/p95 percentiles (p95 highlights tail latency).
• Aggregate by segment to find the slowest: if stt_send_to_stt_recv is high → STT is bottleneck; if llm_send_to_llm_recv high → model latency; if tts_send_to_tts_end high → TTS.
5) Automated CSV / Prometheus (optional)
• To export CSV:
import csv
with open("latency_log.csv","a",newline="") as f:
writer = csv.DictWriter(f, fieldnames=result.keys())
writer.writerow(result)
• To push to Prometheus: use a gateway or expose metrics via client library and record histograms per segment.
6) Next steps I can provide
• A local test script that feeds a test audio file through the exact pipeline and prints per-request stats (useful for model comparison).
• Example code to auto-run comparisons across different LLM or TTS models and produce per-model latency stats.
• Help interpreting your recorded summaries if you paste a few sample results.
Which next step do you want: a local runnable test script, or the comparison harness to test multiple models automatically?polite-dog-12152
12/11/2025, 5:22 AMtall-airline-16756
12/11/2025, 5:22 AMpolite-dog-12152
12/11/2025, 5:50 AMtall-airline-16756
12/11/2025, 5:51 AM# set sample rate and channels to match your input (choose 16000 for SIP/phone or 24000 for web mic)
SAMPLE_RATE = 16000
NUM_CHANNELS = 1
# audio source used for TTS publishing (keep this in your entrypoint)
audio_source = rtc.AudioSource(sample_rate=SAMPLE_RATE, num_channels=NUM_CHANNELS)
# improved VAD settings: faster endpointing, slightly stricter activation
vad = silero.VAD.load(
force_cpu=True,
min_speech_duration=0.08, # detect short speech quickly
min_silence_duration=0.30, # shorter silence to end speech sooner
activation_threshold=0.65 # reduce spurious activations in noisy envs
)
# STT: use streaming STT and match sample rate / channel count
stt_instance = aws.STT(
language="en-US",
number_of_channels=NUM_CHANNELS, # must match audio source
# if number_of_channels > 1: enable_channel_identification=True
)
# Create AgentSession with streaming-friendly settings and lower endpointing
session = AgentSession(
stt=stt_instance,
vad=vad,
preemptive_generation=True,
use_tts_aligned_transcript=True,
# respond faster to turn end:
min_endpointing_delay=0.25,
max_endpointing_delay=2.5,
)
# If you manually stream audio frames (instead of letting AgentSession auto-manage):
# use stt_instance.stream() and push frames directly for low-latency interim results.
# Example:
# stt_stream = stt_instance.stream()
# async for audio_event in rtc.AudioStream(track):
# stt_stream.push_frame(audio_event.frame)
# await stt_stream.aclose()
3) Additional practical tips
• If SIP/phone audio, prefer SAMPLE_RATE=8000 or 16000 depending on carrier; confirm what your SIP gateway provides. Mismatched rates force resampling and cause artifacts.
• If you set number_of_channels > 1, add enable_channel_identification=True to aws.STT to avoid BadRequest errors.
• Reduce VAD min_silence_duration too far only if you see frequent cutoffs; try 0.30s → 0.20s incrementally.
• Use interim STT results to display partial text and begin LLM prep — final transcript can replace interim.
• Run tests with representative noisy audio and measure p50/p95 latency after changes.
4) Want me to:
• Patch your full entrypoint with these exact edits? (I’ll return a ready-to-run diff), or
• Produce a short test script that streams a local WAV through the exact pipeline and prints interim/final timings?
Which option do you want?
Sources: Agent session | LiveKit docs | Smallest AI TTS plugin guide | LiveKit docs | Silero VAD plugin | LiveKit docs | Speech-to-text (STT) models | LiveKit Docs | examples/voice_agents | livekit/livekit_composite | DeepWikipolite-dog-12152
12/11/2025, 5:55 AMtall-airline-16756
12/11/2025, 5:55 AMfrom prometheus_client import start_http_server, Histogram, Counter
import time
# Start Prometheus HTTP server on port 8000
start_http_server(8000)
# Define metrics
STT_DURATION = Histogram("livekit_stt_duration_seconds", "STT processing duration")
STT_PARTIAL_COUNT = Counter("livekit_stt_partial_count", "STT interim results count")
LLM_DURATION = Histogram("livekit_llm_duration_seconds", "LLM inference duration")
LLM_TTFB = Histogram("livekit_llm_ttfb_seconds", "LLM time to first byte/token")
TTS_DURATION = Histogram("livekit_tts_duration_seconds", "TTS synthesis duration")
TTS_TTFB = Histogram("livekit_tts_ttfb_seconds", "TTS time to first byte")
TURN_LATENCY = Histogram("livekit_turn_latency_seconds", "End-to-end turn latency")
USAGE_LLM_TOKENS = Counter("livekit_llm_tokens_total", "Total LLM tokens used")
USAGE_TTS_CHARS = Counter("livekit_tts_chars_total", "Total TTS chars synthesized")
3) Hook into session metrics events
from livekit.agents import metrics, MetricsCollectedEvent
usage_collector = metrics.UsageCollector()
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
# collect built-in usage
usage_collector.collect(ev.metrics)
# handle specific metric types
m = ev.metrics
# STT metrics
if isinstance(m, metrics.STTMetrics):
if getattr(m, "duration", None) is not None:
STT_DURATION.observe(m.duration)
if getattr(m, "partial_count", None) is not None:
STT_PARTIAL_COUNT.inc(m.partial_count)
# LLM metrics
if isinstance(m, metrics.LLMMetrics):
if getattr(m, "duration", None) is not None:
LLM_DURATION.observe(m.duration)
if getattr(m, "ttfb", None) is not None:
LLM_TTFB.observe(m.ttfb)
if getattr(m, "tokens", None) is not None:
USAGE_LLM_TOKENS.inc(m.tokens)
# TTS metrics
if isinstance(m, metrics.TTSMetrics):
if getattr(m, "duration", None) is not None:
TTS_DURATION.observe(m.duration)
if getattr(m, "ttfb", None) is not None:
TTS_TTFB.observe(m.ttfb)
if getattr(m, "chars", None) is not None:
USAGE_TTS_CHARS.inc(m.chars)
4) Record end-to-end turn latency (instrument where you start handling a user turn and when playback finishes)
# on turn start
turn_start = time.time()
# ... process STT/LLM/TTS ...
TURN_LATENCY.observe(time.time() - turn_start)
5) Expose usage summary endpoint or logs (optional)
# periodic summary (async task)
async def emit_usage_summary():
while True:
summary = usage_collector.get_summary()
# log or expose as needed
print("Usage summary:", summary)
await asyncio.sleep(60)
# create task before session.start
asyncio.create_task(emit_usage_summary())
6) Notes
• start_http_server opens /metrics for Prometheus scraping.
• Adjust metric labels if you want to segment by model, region, voice_id, or room.
• Histograms are useful for p50/p95; counters track totals.
• If running multiple workers, either run a metrics exporter per worker and scrape them, or push to a Prometheus Pushgateway.
• Ensure port 8000 is accessible to your Prometheus server or change to an appropriate internal port.
Do you want me to:
• add labeled metrics (e.g., by model name or room_id) and a ready-to-insert diff for your script, or
• provide a Prometheus Pushgateway example for environments where scraping is not possible? Sources: Observability data hooks | LiveKit docs | Agents (Python) | livekit/livekit_composite | DeepWiki | Creating and Publishing Custom Metrics | Self-hosting the Egress Service | LiveKit docs | Self-hosting the Ingress Service | LiveKit docsbrief-dress-9950
02/13/2026, 1:11 PMtall-airline-16756
02/13/2026, 1:12 PMimport asyncio
import wave
import os
from livekit import rtc, api
LIVEKIT_URL = os.getenv("LIVEKIT_URL")
TOKEN = os.getenv("PUBLISHER_TOKEN") # participant token with publish rights
ROOM_NAME = os.getenv("ROOM_NAME", "test-room")
WAV_PATH = "test_call.wav" # replace with your file
async def publish_wav():
room = rtc.Room()
await room.connect(LIVEKIT_URL, TOKEN, room=ROOM_NAME)
# Open WAV and read parameters
with wave.open(WAV_PATH, "rb") as wf:
sample_rate = wf.getframerate()
num_channels = wf.getnchannels()
sampwidth = wf.getsampwidth() # bytes per sample (1=8bit, 2=16bit)
raw = wf.readframes(wf.getnframes())
print(f"WAV: sr={sample_rate}, channels={num_channels}, sampwidth={sampwidth}")
# Create AudioSource matching sample rate & channels
source = rtc.AudioSource(sample_rate=sample_rate, num_channels=num_channels)
track = rtc.LocalAudioTrack.create_audio_track("wav_input", source)
# Publish track
await room.local_participant.publish_track(track)
print("Published WAV track to room")
# Push frames in real-time chunks (20ms frame)
frame_ms = 20
bytes_per_frame = int((sample_rate / 1000) * frame_ms * num_channels * sampwidth)
for i in range(0, len(raw), bytes_per_frame):
chunk = raw[i : i + bytes_per_frame]
# AudioFrame expects PCM16LE when sampwidth==2; ensure your WAV matches that
frame = rtc.AudioFrame(
data=chunk,
sample_rate=sample_rate,
num_channels=num_channels,
samples_per_channel=len(chunk) // (num_channels * sampwidth),
)
await source.capture_frame(frame)
await asyncio.sleep(frame_ms / 1000.0)
# keep connection alive for a bit so agent can finish
await asyncio.sleep(5)
await room.disconnect()
if __name__ == "__main__":
asyncio.run(publish_wav())
agent_entry.py (agent that receives audio and prints transcripts)
import os
import asyncio
from livekit.agents import AgentSession, JobContext, cli, WorkerOptions
from livekit.plugins import aws, silero
from livekit import rtc
# Ensure AWS creds are available in env or IAM
STT_LANGUAGE = "en-US"
SAMPLE_RATE = 16000 # choose to match your WAV file
NUM_CHANNELS = 1
async def entrypoint(ctx: JobContext):
await ctx.connect()
print("Agent connected to room")
# Load VAD (tune if needed)
vad = silero.VAD.load(min_speech_duration=0.08, min_silence_duration=0.3, activation_threshold=0.6)
# Configure AWS STT to match audio
stt = aws.STT(language=STT_LANGUAGE, number_of_channels=NUM_CHANNELS)
# Create AgentSession; AgentSession will subscribe to participant tracks
session = AgentSession(stt=stt, vad=vad, preemptive_generation=True)
# Hook to conversation items (so you see final transcript via AgentSession if configured)
@session.on("conversation_item_added")
def on_conv(ev):
item = getattr(ev, "item", None)
if item and getattr(item, "content", None):
print(f"[CONV] {item.role}: {item.content}")
# Start the session to begin processing incoming audio
await session.start(room=ctx.room, agent=None) # agent=None is fine for pure STT testing
print("Session started. Listening for audio...")
# Keep running until room disconnects
await ctx.wait_for_termination()
if __name__ == "__main__":
# Run the agent worker (use your LiveKit CLI/worker invocation in production)
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
How to run the test
1. Start your agent worker (agent_entry.py) so it joins the same ROOM_NAME.
◦ Ensure the agent has rights to subscribe to participant tracks.
1. Run publisher.py to stream the WAV into the room.
2. Watch the agent logs — you should see interim/final transcripts printed via session events or STT callbacks.
Notes & tips
• Sample rate & channels: make sure the WAV sample_rate and num_channels match the AudioSource you create and the STT configuration (mismatches cause resampling latency/quality loss). Telephony often uses 8000 or 16000 Hz, mono.
• Frame size: using ~20ms frames simulates real-time. Adjust if needed.
• If using aws.STT and number_of_channels > 1, set enable_channel_identification=True.
• If you want explicit interim/final STT events instead of AgentSession conversation items, use stt.stream() and process events yourself (push frames to stt_stream.push_frame()).
• For repeatable tests, use a short WAV (few seconds) and run multiple times to collect latency/accuracy stats.
• If you are testing telephony integration specifically, publish the WAV through your telephony gateway into LiveKit instead of publisher.py — but publisher.py simulates the audio input side for the agent.
Would you like:
• A version that uses stt.stream() and prints interim transcripts as soon as they arrive?
• A small test harness that runs multiple WAVs and writes per-turn latency and transcripts to CSV for further analysis? Sources: examples/voice_agents | livekit/livekit_composite | DeepWiki | Capturing the First Few Seconds of a Call for Processing | Playing Audio | LiveKit Documentation