store: NotGivenOr[bool] = NOT_GIVEN, metadata:...
# ask-ai
p
store: NotGivenOr[bool] = NOT_GIVEN, metadata: NotGivenOr[dict[str, str]] = NOT_GIVEN, max_completion_tokens: NotGivenOr[int] = NOT_GIVEN, timeout: Timeout | None = None, service_tier: NotGivenOr[str] = NOT_GIVEN, reasoning_effort: NotGivenOr[ReasoningEffort] = NOT_GIVEN, verbosity: NotGivenOr[Verbosity] = NOT_GIVEN, _provider_fmt: NotGivenOr[str] = NOT_GIVEN, _strict_tool_schema: bool = True
t
Thanks for reaching out, arpan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're sending a snippet of parameter declarations. I can help — what do you want to do with these parameters? To guide you quickly, please tell me one of the following: • Are you asking what each parameter means (type/usage)? • Do you want help validating or formatting these for a specific SDK or API call? • Are you seeing an error when using these parameters? If so, paste the error and the minimal code snippet that triggers it. • Do you want examples showing how to set these values in code (which language)? Pick one and I’ll provide a concise, targeted next step.
p
tell me aour openali llm prameters and give examles
t
You're asking for the OpenAI LLM parameters and examples — here are the supported options and quick examples in Python and TypeScript. Parameters • model (string, optional) — Model name. Default: "gpt-4o-mini". • temperature (float, optional) — Controls randomness (0.0–2.0). Default: 0.8. • tool_choice (enum: "auto" | "required" | "none", optional) — Controls tool usage. Default: "auto". • base_url / api_key (optional) — Override to use API-compatible providers or custom endpoints. Python example
Copy code
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",
        # base_url="https://custom-api.example", api_key="KEY"  # optional
    ),
    # ... tts, stt, vad, etc.
)
TypeScript example
Copy code
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 Docs
p
more info
t
You asked for more info about OpenAI LLM parameters — below are expanded explanations for the additional parameters you mentioned and concise Python/TypeScript examples showing how to set them in LiveKit. Parameters (expanded) • store (bool | NotGiven) — Whether to store the conversation or artifacts. Use True/False to enable/disable storing; leave as NotGiven to use default behavior. • metadata (dict[str,str] | NotGiven) — Arbitrary key/value metadata attached to requests (e.g., {"user_id":"1234","session":"signup"}). • max_completion_tokens (int | NotGiven) — Limits tokens in the model's completion. Provide an integer (e.g., 300) to cap response length. • timeout (Timeout | None) — Request timeout configuration. Set a Timeout object or None for no custom timeout. • service_tier (str | NotGiven) — Selects provider service tier (billing/priority). Pass a tier string when supported by provider. • reasoning_effort (ReasoningEffort | NotGiven) — Controls internal reasoning intensity (e.g., "low", "medium", "high") for models that support it. • verbosity (Verbosity | NotGiven) — Controls how verbose the agent’s internal logging or responses are (values depend on SDK enums). • _provider_fmt (str | NotGiven) — Provider-specific formatting option; pass provider-specific format string when needed. • _strict_tool_schema (bool) — When True, enforces strict validation of tool input/output schemas. Notes • Many of these are pass-through/provider-specific options and may require using
extra_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:
Copy code
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:
Copy code
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:
Copy code
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:
Copy code
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 docs
p
how to add emption in output response
t
You're asking how to add emotion to LLM outputs in LiveKit — here are the practical methods you can use and short examples to implement each. Pick which approach you'd like a fuller code example for. 1) Use
instructions
(system prompt) — simplest, most effective • Add emotional guidance to the LLM system prompt and to TTS instructions for consistent text + speech tone. • Example (Python):
Copy code
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:
Copy code
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:
Copy code
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 docs
p
11 labd tts
t
It looks like you mean ElevenLabs TTS. Do you want: • Step-by-step setup (install + API key + basic example), • A code example showing ElevenLabs TTS wired to an OpenAI LLM (Python or TypeScript), • How to add emotion/expressiveness with ElevenLabs (SSML, stability/similarity, voice selection), or • Troubleshooting for a specific error? Tell me which and which language (Python or TypeScript) and I’ll provide the exact steps or code. Sources: ElevenLabs TTS plugin guide | LiveKit Docs | ElevenLabs TTS | LiveKit Docs
p
A code example showing ElevenLabs TTS wired to an OpenAI LLM (Python
t
Below is a concise Python example showing how to wire ElevenLabs TTS with an OpenAI LLM inside a LiveKit AgentSession. It includes installation notes, environment variables, and a minimal runnable pattern. 1) Installation (Python) • Add LiveKit agents with ElevenLabs and OpenAI plugin support: uv add "livekit-agents[elevenlabs,openai]~=1.2" 2) Environment • In your .env: ELEVEN_API_KEY=your_eleven_api_key OPENAI_API_KEY=your_openai_api_key 3) Minimal example (Python)
Copy code
from 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?
p
11 labs all pameter examples
t
Below are all ElevenLabs TTS parameters supported in LiveKit (concise descriptions) plus Python examples for each. If you want a TypeScript version or a combined LLM+TTS sample, tell me which and I’ll provide it. Parameters (ElevenLabs TTS plugin) • model (str) — TTS model to use. Defaults:
eleven_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)
Copy code
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
Copy code
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
Copy code
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
Copy code
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 Docs
p
• 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.
t
Below is a concise, runnable Python example showing the full flow: • LLM returns structured JSON: {"response":"...", "emotion":"happy"} • Map emotion → ElevenLabs
voice_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
Copy 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?
p
stt=stt.SpeechStream( stt=aws.STT(language="en-US",number_of_channels=1), sample_rate=24000, ),
t
You can’t wrap
aws.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)
Copy code
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)
Copy code
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 docs
p
error=BadRequestException('You need to be enable Channel Identification while specifying number of channels in the request. Please enable Channel Identification and try again.')
t
You're seeing the Transcribe error because you specified
number_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:
Copy code
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 Docs
p
import sys import time import uuid import logging import asyncio from datetime import datetime from livekit import api, rtc from livekit.agents import ( JobContext, AgentSession, RoomInputOptions, JobProcess, UserStateChangedEvent, RoomOutputOptions, ConversationItemAddedEvent, ChatContext, ModelSettings ) from livekit.plugins import silero, noise_cancellation from src.utils.exception import CustomException from src.constants.agent_config import SecretsConfig from src.services.session_manger import CustomerSessionInfo from src.voice_agent.voice_agent import HolionixAgent from src.tools.tools import ( web_tool, create_lost_baggage_ticket, check_lost_baggage_status, transfer_call ) secrets = SecretsConfig() def prewarm(proc: JobProcess): proc.userdata["vad"] = silero.VAD.load() async def entrypoint(ctx: JobContext): """Main entrypoint for the LiveKit agent""" try: inactivity_task: asyncio.Task | None = None room_id = str(uuid.uuid4()) print(room_id) ctx.log_context_fields = { "room": ctx.room.name, } # ✅ Start Recording req = api.RoomCompositeEgressRequest( room_name=ctx.room.name, audio_only=True, file_outputs=[ api.EncodedFileOutput( file_type=api.EncodedFileType.MP4, filepath=f"recordings/{room_id}_{datetime.now().strftime('%Y-%m-%d %H-%M-%S')}", s3=api.S3Upload( access_key=secrets.AWS_ACCESS_KEY_ID, secret=secrets.AWS_SECRET_ACCESS_KEY, region=secrets.AWS_REGION, bucket=secrets.AWS_RECODING_BUCKET, ), ), ], ) lkapi = api.LiveKitAPI( api_key=secrets.LIVEKIT_API_KEY, api_secret=secrets.LIVEKIT_API_SECRET, url=secrets.LIVEKIT_URL, ) await lkapi.egress.start_room_composite_egress(req) await lkapi.aclose() print("🚀 Starting LiveKit agent...") await ctx.connect() print("⏳ Waiting for participant...") participant = await ctx.wait_for_participant() audio_source = rtc.AudioSource( sample_rate=24000, num_channels=1 ) tts_track = rtc.LocalAudioTrack.create_audio_track( "model-tts-audio", audio_source ) await ctx.room.local_participant.publish_track(tts_track) try: phone = participant.attributes["sip.phoneNumber"] except Exception: phone = "Web_User" session_manager = CustomerSessionInfo( room_id=room_id, session_id=ctx.room.name, ) print("🔧 Creating session components...") try: vad = silero.VAD.load( force_cpu=True, min_silence_duration=0.25, ) session = AgentSession( preemptive_generation=True, use_tts_aligned_transcript=True, ) print("✅ VAD & Session ready") except Exception as e: print(f"❌ Session init failed: {e}") raise CustomException(e, sys) is_sip_call = ( hasattr(participant, "kind") and participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP ) session_manager.start_session(participant=participant) initial_context = ChatContext() initial_context.add_message( role="system", content=f""" You are a professional customer support voice agent. Customer phone number is {phone} """, ) agent = HolionixAgent( tools=[web_tool, create_lost_baggage_ticket, check_lost_baggage_status,transfer_call], chat_ctx=initial_context, ctx=ctx, ) asyncio.create_task( agent.stream_llm_to_tts( chat_ctx=initial_context, audio_source=audio_source, # ✅ THIS is what feeds the voice tools=agent.tools, model_settings=ModelSettings(), room=ctx.room, ) ) async def user_presence_task(): for _ in range(2): await session.generate_reply( instructions="The user has been inactive. Politely check if the user is still present." ) await asyncio.sleep(20) await asyncio.shield(session.aclose()) ctx.delete_room() time.sleep(4) @session.on("user_state_changed") def _user_state_changed(ev: UserStateChangedEvent): nonlocal inactivity_task if ev.new_state == "away": inactivity_task = asyncio.create_task(user_presence_task()) return if inactivity_task: inactivity_task.cancel() await session.start( agent=agent, room=ctx.room, room_input_options=RoomInputOptions( audio_enabled=True, noise_cancellation=noise_cancellation.BVCTelephony(), ), room_output_options=RoomOutputOptions( transcription_enabled=True, sync_transcription=False, ), ) print("✅ Session started") print("🎙️ Agent is now active") # async def process_audio_track(track: rtc.RemoteAudioTrack): # stt = agent.stt # 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() @session.on("conversation_item_added") def on_conversation_item(event: ConversationItemAddedEvent): if hasattr(event, "item"): item = event.item if hasattr(item, "content") and item.content: speaker = ( "USER" if hasattr(item, "role") and item.role == "user" else "AGENT" ) session_manager.log_transcription( text=item.content, speaker=speaker ) @ctx.room.on("participant_disconnected") def on_participant_disconnected(participant): if session_manager: print(f"📞 Call ended: {participant.identity}") session_manager.close_transcription() @ctx.room.on("disconnected") def on_room_disconnected(): ctx.delete_room() print(f"✅ Room {ctx.room.name} deleted") ctx.add_shutdown_callback(agent.metrics_store) except Exception as e: print(f"❌ Voice agent error: {e}") raise CustomException(e, sys) if name == "__main__": from livekit.agents import cli, WorkerOptions cli.run_app( WorkerOptions( entrypoint_fnc=entrypoint, #agent_name="telephony_agent", initialize_process_timeout=100, job_memory_warn_mb=1900, multiprocessing_context="forkserver", api_key=secrets.LIVEKIT_API_KEY, api_secret=secrets.LIVEKIT_API_SECRET, ws_url=secrets.LIVEKIT_URL, ) )
t
Thanks — I see your full agent script. Which specific issue do you want me to help with right now? For example: • The earlier AWS Transcribe BadRequestException about channel identification? • STT not transcribing or streaming correctly? • TTS synthesis or emotion mapping failing? • AgentSession start/track publish errors or egress/upload failures? If it's the channel-identification error, confirm: • What value do you set for
num_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.
p
i fail to understand speech
t
I’m sorry you’re running into this — let’s narrow down what “fail to understand speech” means so I can give a targeted fix. Which of these best describes the problem? Pick one (or paste a short recording/error/output): • STT transcripts are wrong (words mis‑recognized or garbled). • No transcript appears at all (silence / no events). • The agent hears but LLM responses are irrelevant (understanding vs. transcription issue). • TTS audio is unclear (synthesized speech is hard to understand). • Channel/format mismatch (stereo vs mono, sample rate) causing distortion. Also please share these minimal details: 1.
number_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).
p
like i am tell english it take oh
t
Thanks — I can help fix that. A few quick clarifying questions so I give the exact changes that matter: 1. Which STT language are you using? (e.g.,
"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.
p
how to get fast response from aws stt
t
To get faster responses from AWS STT in your LiveKit voice agent, focus on reducing capture/processing latency and using streaming with partial results. Below are concise, actionable steps and a short code example you can apply. Key recommendations • Use streaming STT (push frames to stt.stream()) so transcription happens continuously instead of waiting for full audio chunks. • Enable partial/real-time results if supported by the STT plugin (streaming returns interim transcripts sooner). • Match sample rates exactly: set rtc.AudioSource.sample_rate to the same value your STT expects (16000 or 24000). Mismatch causes resampling delay. • Minimize chunking/ buffering: reduce chunk_length_schedule or streaming_latency on the TTS/STT side if present. • Use mono (1 channel) when possible; if multi-channel, set number_of_channels correctly and enable channel identification (adds processing but avoids errors). • Use a lightweight VAD so you send only speech frames; keep VAD min_silence_duration small (e.g., 0.15–0.25s) to detect speech quickly. • Reduce model-side processing: choose faster STT options/regions and avoid heavy post-processing or expensive vocab lookups in-line. • Network: run STT region close to your LiveKit worker and ensure low jitter/packet loss. Minimal streaming example (Python)
Copy code
from 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.
p
i want calculate latence find what segmait of model make more latency
t
I can help you measure end-to-end latency and pinpoint which segment (capture, network, STT, LLM, TTS, playback) adds the most delay. Quick plan — I’ll give a short checklist and small instrumenting snippets you can add to your Python agent to get per-segment timings. Do you want to measure in production (real calls) or locally with a test audio file? If production, I’ll show: • where to add timestamps (capture, STT send/recv, LLM send/recv, TTS send/recv, playback), • how to record interim vs final STT timings, • how to aggregate and report per-segment percentiles. If local/test, I’ll provide a runnable script that: 1) plays a test clip into your pipeline, 2) captures timestamps at each handoff, 3) prints per-request breakdown and summary stats (mean, p50, p95). Which mode do you want to start with — production instrumentation or local test script?
p
yes
t
Great — I'll provide a concise production instrumentation plan and a small Python snippet you can drop into your agent to measure per-segment latency (capture → STT → LLM → TTS → playback). This will help identify which segment (or model) adds the most delay. What I’ll give you: • Where to add timestamps in your existing flow. • A compact helper class to record timestamps and compute per-request breakdowns. • Example integration points in your script (async STT stream, LLM call, TTS synth). • Suggestions for aggregating and exporting metrics (logs, Prometheus, CloudWatch). Confirm one detail before I produce the code: do you call STT via
AgentSession
(session.start with
stt=aws.STT(...)
) or do you push frames manually with
stt.stream()
?
p
i want to calculate
t
Below is a concise, drop-in Python instrumentation helper and example integration showing where to add timestamps in your LiveKit agent flow to measure per-segment latency: capture → STT send/receive (interim/final) → LLM send/receive → TTS synth → playback. It logs per-request timings and a running summary (count, mean, p50, p95). Adapt method names if your SDK versions differ. 1) Helper class (latency recorder)
Copy code
import 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:
Copy code
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):
Copy code
# 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:
Copy code
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:
Copy code
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:
Copy code
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?
p
from dotenv import load_dotenv import os from livekit.agents import metrics, MetricsCollectedEvent usage_collector = metrics.UsageCollector() from livekit import agents, rtc from livekit.agents import AgentSession, Agent,stt,tts from livekit.plugins import noise_cancellation, silero,elevenlabs,openai,aws from livekit.plugins.turn_detector.multilingual import MultilingualModel load_dotenv(".env") class Assistant(Agent): def __init__(self) -> None: super().__init__( instructions="""You are a helpful voice AI assistant. You eagerly assist users with their questions by providing information from your extensive knowledge. Your responses are concise, to the point, and without any complex formatting or punctuation including emojis, asterisks, or other symbols. You are curious, friendly, and have a sense of humor.""", ) async def my_agent(ctx: agents.JobContext): session = AgentSession( stt=aws.STT(language="en-US",language_model_name="us_engclm",vocab_filter_name="English",vocab_filter_method="mask",vocabulary_name="bajaj"), llm=openai.LLM(api_key=os.getenv("OPENAI_API_KEY"),temperature=0.6,max_completion_tokens=300,model="gpt-4o-mini",prompt_cache_key="24h",tool_choice="auto"), tts=tts.StreamAdapter( tts=elevenlabs.TTS( model="eleven_turbo_v2_5", api_key=os.getenv("ELEVENLABS_API_KEY"), voice_id="204jSNMxoKiZqmO2dePr", voice_settings=elevenlabs.VoiceSettings( stability=0.7, similarity_boost=0.85, style=0.6, use_speaker_boost=True, speed=1.2 ), enable_ssml_parsing=True, ), text_pacing=True ), #vad=silero.VAD.load(), #turn_detection=MultilingualModel(), ) await session.start( room=ctx.room, agent=Assistant(), ) @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): usage_collector.collect(ev.metrics) async def log_usage(): summary = usage_collector.get_summary() print(f"Usage: {summary}") await session.generate_reply( instructions="Greet the user and offer your assistance." ) if name == "__main__": from livekit.agents import cli, WorkerOptions cli.run_app( WorkerOptions( entrypoint_fnc=my_agent, #agent_name="telephony_agent", initialize_process_timeout=100, job_memory_warn_mb=1900, multiprocessing_context="forkserver", ) )
t
Thanks — I see your agent code. Do you want me to: • add per-segment latency instrumentation (STT→LLM→TTS→playback) into this script, or • fix STT accuracy/latency (channel/sample-rate/VAD) issues, or • improve metrics export (CSV/Prometheus)? Pick one and I’ll provide the exact code changes to drop into your script.
p
fix STT accuracy/latency (channel/sample-rate/VAD) issues
t
Thanks — I’ll give a concise, actionable patch for your script to improve STT accuracy and latency (sample rate, channels, VAD, endpointing, streaming). Apply the changes below. 1) Key changes • Match capture/sample rate across AudioSource and STT (use 16000 for telephony, 24000 for web mics). • Ensure mono where possible: num_channels=1 and number_of_channels=1. If multi-channel, enable channel identification. • Load Silero VAD with lower endpointing delay (faster detection) and slightly higher activation threshold to reduce false starts. • Use streaming STT so interim transcripts arrive quickly. • Reduce AgentSession endpointing delays. 2) Minimal patch to integrate into your code (drop-in changes)
Copy code
# 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 | DeepWiki
p
Prometheus
t
I'll show a concise Prometheus integration you can drop into your script to export STT/LLM/TTS latency and usage metrics. 1) Install prometheus client • pip install prometheus_client 2) Add this snippet near your imports and before session start
Copy code
from 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
Copy code
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)
Copy code
# 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)
Copy code
# 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 docs
b
Can you show me how I'd do a test where I pass in a wav file into the Livekit pipeline so that I can test to see if it can transcribe accordingly? I'd like to do it over telephony if possible (I will handle the telephony part, just show me how I'd do the actual test and pass in a wav file instead of having a user speak
t
Great — below is a focused, runnable Python test you can drop into your environment to simulate a telephony call by feeding a WAV file into the LiveKit pipeline. It demonstrates publishing the WAV as a LocalAudioTrack (so the agent receives it like a real caller), and shows a simple agent that subscribes and prints interim/final STT results. Use this to validate STT accuracy and latency. Before you run • Install dependencies: pip install livekit-client livekit-agents[aws,elevenlabs,openai] prometheus_client (only if using metrics) • Ensure your .env contains valid LiveKit URL + keys and any STT provider keys (AWS creds if using aws.STT). • Choose a WAV file with matching sample rate & channels (telephony: 16000 Hz mono preferable). Files: 1) publisher.py — connects as a participant and streams the WAV file into the room. 2) agent_entry.py — an example agent (or adapt your existing agent) that subscribes to incoming audio and uses STT. publisher.py (publishes WAV as a LocalAudioTrack)
Copy code
import 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)
Copy code
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