narrow-pager-84057
11/29/2025, 8:57 AMtall-airline-16756
11/29/2025, 8:57 AMtall-airline-16756
11/29/2025, 8:57 AMstt_node and push them into the LLM context as they arrive. Example pattern:
a. On INTERIM_TRANSCRIPT, append or update a user message in the chat context (without finalizing).
b. On FINAL_TRANSCRIPT, mark that message final and commit it.
• Override llm_node (or stream into your chat loop) so the LLM can process partial updates rather than waiting for a completed turn. Yield incremental tokens/responses as the LLM produces them.
• Reduce reliance on silence-based turn commits:
◦ Use manual turn control or shorten VAD silence thresholds.
◦ Use LiveKit’s End-of-Utterance model or tune turn-detection to detect earlier EOU.
• Debounce or rate-limit interim updates so you don’t overwhelm the LLM or trigger too-frequent tool calls (e.g., send interim updates every 200–500ms or when significant punctuation/length change occurs).
• If latency is critical, consider realtime models that process audio directly (bypass STT→LLM separation) for true end-to-end streaming.
If you’d like, tell me:
• which STT provider and LLM you’re using,
• whether you currently override stt_node or llm_node, and
• how your turn detection is configured (automatic VAD, manual, or EOU model)
I’ll give code-specific guidance for your stack and a recommended debounce strategy.
Sources: Turn detection and interruptions | LiveKit Docs | Improving voice AI's turn detection with transformers | Realtime model plugins | LiveKit Docs | Speech-to-text (STT) models | LiveKit Docsnarrow-pager-84057
11/29/2025, 8:58 AMtall-airline-16756
11/29/2025, 8:59 AMenable_partials=True so it emits INTERIM_TRANSCRIPT events.
2) Forward interim events from stt_node
• Override stt_node to yield interim events immediately instead of only final transcripts. On each INTERIM_TRANSCRIPT, update or upsert a user message in the chat context (do not mark final). On FINAL_TRANSCRIPT, mark final and commit.
3) Stream partials into the LLM
• Override llm_node (or call the LLM directly from your chat loop) to consume incremental updates from the chat context and stream responses back (token-by-token if GPT‑5.1 supports streaming).
• Use preemptive_generation or start an LLM stream when a significant partial arrives so the model can begin reasoning before finalization.
4) Debounce and threshold interim updates
• Avoid calling the LLM for every tiny partial. Use a simple debounce (e.g., 200–500ms) or length/clarity thresholds (e.g., line length > X or punctuation keywords) to trigger speculative LLM calls.
• On final transcript, cancel/replace speculative outputs if the final content differs.
5) Reduce reliance on silence-based turn commits
• Use semantic/EOU turn detection (LiveKit’s transformer-based EOU) or manual turn control instead of long VAD silence windows so commits don’t wait for long pauses.
6) Handle tool calls earlier
• If a tool should trigger from partial content (keywords or intents), detect those in stt_node or in your partial-buffer logic and invoke the tool proactively (with safeguards to reconcile if final transcript changes).
• Alternatively, have the LLM produce a provisional tool-call intent which you confirm/execute on finalization.
7) Practical flow summary (minimal code outline)
• stt_node -> yield INTERIM_TRANSCRIPT events
• partial buffer in agent -> update chat context
• debounce timer / threshold -> start llm.chat(stream=True) with current partials
• stream LLM tokens back, handle speculative tool intents
• on FINAL_TRANSCRIPT -> finalize message, reconcile/cancel speculative responses, perform confirmed tool calls
If you want, I can:
• Provide a focused code example for Speechmatics + GPT‑5.1 in your agent (stt_node + partial buffering + llm_node streaming).
• Recommend exact debounce timings and threshold heuristics based on your expected utterance lengths. Which would you prefer? Sources: Sending text | LiveKit docs | Speechmatics STT plugin guide | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs | External data and RAG | LiveKit Docs | Improving voice AI's turn detection with transformersnarrow-pager-84057
11/29/2025, 9:05 AMtall-airline-16756
11/29/2025, 9:06 AMimport asyncio
from typing import AsyncIterable, Optional
from livekit import agents, rtc
from livekit.agents import Agent, AgentSession, ChatContext, ChatMessage
from livekit.plugins import speechmatics, openai
from livekit.agents.llm import ChatChunk
# Tunable parameters
PARTIAL_DEBOUNCE_SEC = 0.25 # wait before sending partial to LLM
MIN_PARTIAL_LEN = 12 # minimum characters before sending speculative calls
class LowLatencyVoiceAgent(Agent):
def __init__(self):
super().__init__(instructions="Fast streaming agent.")
# buffer and synchronization primitives
self._partial_text = ""
self._partial_lock = asyncio.Lock()
self._partial_event = asyncio.Event()
self._speculative_task: Optional[asyncio.Task] = None
async def stt_node(
self,
audio: AsyncIterable[rtc.AudioFrame],
model_settings: agents.ModelSettings,
) -> Optional[AsyncIterable[agents.stt.SpeechEvent]]:
# Configure Speechmatics with partials enabled
stt = speechmatics.STT(enable_partials=True, language="en")
stream = stt.stream()
# feed audio frames into STT stream
async def feed_audio():
async for frame in audio:
stream.push_frame(frame)
await stream.end_input_async()
asyncio.create_task(feed_audio())
# consume STT events and update partial buffer immediately
async for event in stream:
# event.type will be INTERIM_TRANSCRIPT or FINAL_TRANSCRIPT
if event.type == agents.stt.SpeechEventType.INTERIM_TRANSCRIPT:
text = event.alternatives[0].text
async with self._partial_lock:
self._partial_text = text
self._partial_event.set() # notify debounce/llm loop
# still yield the event so other nodes can observe it
yield event
elif event.type == agents.stt.SpeechEventType.FINAL_TRANSCRIPT:
full = event.alternatives[0].text
# finalize: clear partials and signal final
async with self._partial_lock:
self._partial_text = ""
self._partial_event.set()
# append final message to chat context so LLM has authoritative content
self.chat.add_message(role="user", content=full, final=True)
# yield final so downstream nodes can act
yield event
else:
yield event
async def _speculative_llm_loop(self, chat_ctx: ChatContext):
"""
Background loop: waits for partial_event, debounces, then sends
speculative partials to LLM (streaming). Repeats until final arrives.
"""
llm = openai.LLM(model="gpt-5.1") # replace with your GPT-5.1 binding
speculative_stream = None
while True:
await self._partial_event.wait()
self._partial_event.clear()
async with self._partial_lock:
partial = self._partial_text
# stop if no meaningful partial
if not partial or len(partial.strip()) < MIN_PARTIAL_LEN:
# if an existing speculative stream exists, cancel it
if speculative_stream:
speculative_stream.cancel()
speculative_stream = None
# if partial is empty, could be finalization: break loop if final queued
# continue listening
continue
# debounce small updates
try:
await asyncio.sleep(PARTIAL_DEBOUNCE_SEC)
except asyncio.CancelledError:
return
# check whether partial updated during sleep
async with self._partial_lock:
current_partial = self._partial_text
if not current_partial or current_partial == partial:
# launch speculative streaming LLM call with current partial
temp_ctx = chat_ctx.clone()
# mark as speculative to help reconcile later
temp_ctx.add_message(role="user", content=current_partial + " [PARTIAL]")
# cancel previous speculative stream if running
if speculative_stream:
speculative_stream.cancel()
# start streaming LLM response (token-by-token)
async def run_stream():
try:
async for chunk in llm.chat(temp_ctx, stream=True):
# stream token chunks back to client immediately
# chunks are ChatChunk objects; yield them via agent response mechanism
await self.send_chat_chunk(chunk)
except asyncio.CancelledError:
# speculative call cancelled on finalization
return
speculative_stream = asyncio.create_task(run_stream())
async def send_chat_chunk(self, chunk: ChatChunk):
"""
Helper: integrate ChatChunk into output path.
Implementation detail depends on how you're sending assistant tokens to clients.
Here we call a generic assistant output method.
"""
# Example: yield tokens to connected consumers or call agent-side emitters
await self.emit_assistant_chunk(chunk)
async def on_session_start(self, session: AgentSession):
# start speculative LLM background loop bound to chat context
self._speculative_task = asyncio.create_task(self._speculative_llm_loop(self.chat))
async def on_session_end(self, session: AgentSession):
if self._speculative_task:
self._speculative_task.cancel()
self._speculative_task = None
# Example llm_node that processes finalized chat context (final transcript)
async def llm_node(
self,
chat_ctx: ChatContext,
tools,
model_settings: agents.ModelSettings,
) -> AsyncIterable[ChatChunk]:
# On finalization, call LLM to produce authoritative response and confirmed tool calls
llm = openai.LLM(model="gpt-5.1")
async for chunk in llm.chat(chat_ctx, stream=True):
yield chunk
# Usage / session bootstrap
async def main():
session = AgentSession(
stt=None, # handled by stt_node
llm=None, # handled by llm_node
# optional: use semantic/EOU turn detection if available
# turn_detection=agents.EOUTurnDetection()
)
agent = LowLatencyVoiceAgent()
await session.start(room="YOUR_ROOM_ID", agent=agent) # Wire up to LiveKit room/audio
if __name__ == "__main__":
asyncio.run(main())
If you want, I can:
• convert this into a fully working sample that wires to a real LiveKit room/audio track and includes a sample tool (web search) with early speculative invocation, or
• provide a trimmed version that focuses strictly on minimal-latency token streaming without speculative tool handling.
Which would you like next?
Sources: Speechmatics STT plugin guide | LiveKit Docs | Events and error handling | LiveKit docsnarrow-pager-84057
11/29/2025, 9:07 AMtall-airline-16756
11/29/2025, 9:07 AMfrom livekit.agents import AgentSession
from livekit.plugins.turn_detector.multilingual import MultilingualModel
session = AgentSession(
stt="speechmatics/stt:en", # streaming STT with interim partials
llm="openai/gpt-5.1", # streaming-capable LLM (ChatGPT-5.1)
tts=None, # optional; omit if not needed
vad=None, # let STT handle VAD/partials
turn_detection=MultilingualModel(), # semantic EOU reduces wait-for-silence
preemptive_generation=True, # start LLM generation on partials
voice_options={
"partial_debounce_ms": 250, # debounce partial updates (tune 200–500ms)
"min_partial_chars": 12, # ignore tiny partials
},
)
Node.js preset equivalent:
import { AgentSession } from "@livekit/agents";
import { MultilingualModel } from "@livekit/turn-detector";
const session = new AgentSession({
stt: "speechmatics/stt:en",
llm: "openai/gpt-5.1",
tts: undefined,
vad: undefined,
turnDetection: new MultilingualModel(),
preemptiveGeneration: true,
voiceOptions: {
partialDebounceMs: 250,
minPartialChars: 12,
},
});
Why these settings reduce latency
• speechmatics/stt:en emits INTERIM_TRANSCRIPT events so you can act on partials immediately.
• preemptive_generation=True starts LLM work on partials rather than waiting for FINAL_TRANSCRIPT.
• Multilingual semantic turn detection detects end-of-utterance earlier than long VAD silence windows.
• Debounce and min-partial thresholds avoid noisy micro-updates and limit unnecessary LLM calls.
Tuning tips
• Lower partial_debounce_ms (e.g., 150–250ms) for faster responses; raise it if you see too many useless partials.
• Lower min_partial_chars to react earlier for short commands; raise it to reduce false triggers.
• If you need extreme latency reduction, consider realtime LLMs (audio→LLM) instead of STT→LLM.
If you want, I can:
• produce a one-file runnable example wiring this preset to a LiveKit room/audio track, or
• suggest exact debounce/minimum settings for your expected utterance length (short commands vs long dictation). Which would you prefer? Sources: Voice AI quickstart | LiveKit docs | Speech-to-text (STT) models | LiveKit Docs | Agent speech and audio | LiveKit docs | examples/bank-ivr | livekit/livekit_composite | DeepWiki | Models | LiveKit Docsnarrow-pager-84057
11/29/2025, 9:21 AMtall-airline-16756
11/29/2025, 9:21 AMenable_partials=True (Speechmatics) so it emits INTERIM_TRANSCRIPT events.
• Allow preemptive/partial LLM generation: set preemptive_generation=True or use a streaming-capable LLM model so the LLM can start on partials.
• Turn-detection/VAD: prefer semantic/EOU turn detection or shorten VAD so commits don’t wait for long silence.
• Optional (no custom class needed): use AgentSession preset with those flags (see earlier preset). If you need finer control, override stt_node to forward interim events and/or llm_node to consume partials.
If you want, I can show the minimal AgentSession config or the small `stt_node`/`llm_node` snippets to wire this for Speechmatics → OpenAI streaming. Which would you prefer?narrow-pager-84057
11/29/2025, 9:22 AMtall-airline-16756
11/29/2025, 9:23 AMstt_node override that yields INTERIM_TRANSCRIPT and FINAL_TRANSCRIPT events and updates a small partial buffer.
• a lightweight partial-to-LLM loop that debounces partials, starts a streaming LLM call on meaningful partials, and reconciles on final transcripts.
• notes on cancellation/reconciliation.
Drop into your Agent subclass (only the relevant methods shown). Replace model identifiers and I/O hooks with your environment.
import asyncio
from typing import AsyncIterable, Optional
from livekit import agents, rtc
from livekit.agents import Agent, ChatContext
from livekit.plugins import speechmatics, openai
from livekit.agents.stt import SpeechEvent, SpeechEventType
PARTIAL_DEBOUNCE = 0.25 # seconds
MIN_PARTIAL_CHARS = 12
class PartialStreamingAgent(Agent):
def __init__(self):
super().__init__(instructions="Streaming agent")
self._partial = "" # current interim text
self._partial_lock = asyncio.Lock()
self._partial_event = asyncio.Event()
self._spec_task: Optional[asyncio.Task] = None
self._spec_stream_task: Optional[asyncio.Task] = None
# STT node: enable partials and update buffer
async def stt_node(
self,
audio: AsyncIterable[rtc.AudioFrame],
model_settings: agents.ModelSettings,
) -> Optional[AsyncIterable[SpeechEvent]]:
stt = speechmatics.STT(enable_partials=True, language="en")
sstream = stt.stream()
async def feed():
async for frame in audio:
sstream.push_frame(frame)
await sstream.end_input_async()
asyncio.create_task(feed())
async for event in sstream:
if event.type == SpeechEventType.INTERIM_TRANSCRIPT:
text = event.alternatives[0].text
async with self._partial_lock:
self._partial = text
self._partial_event.set()
yield event
elif event.type == SpeechEventType.FINAL_TRANSCRIPT:
final_text = event.alternatives[0].text
# add final to chat context (authoritative)
self.chat.add_message(role="user", content=final_text, final=True)
# clear partial buffer and notify speculative loop to reconcile
async with self._partial_lock:
self._partial = ""
self._partial_event.set()
yield event
else:
yield event
# Called when session starts: start speculative loop
async def on_session_start(self, session: agents.AgentSession):
self._spec_task = asyncio.create_task(self._speculative_loop(self.chat))
async def on_session_end(self, session: agents.AgentSession):
if self._spec_task:
self._spec_task.cancel()
self._spec_task = None
if self._spec_stream_task:
self._spec_stream_task.cancel()
self._spec_stream_task = None
# Debounce partials and start/cancel speculative streaming LLM calls
async def _speculative_loop(self, chat_ctx: ChatContext):
llm = openai.LLM(model="gpt-5.1") # use streaming-capable LLM binding
while True:
await self._partial_event.wait()
self._partial_event.clear()
# snapshot partial safely
async with self._partial_lock:
partial = self._partial
# if no meaningful partial, cancel speculative stream
if not partial or len(partial.strip()) < MIN_PARTIAL_CHARS:
if self._spec_stream_task:
self._spec_stream_task.cancel()
self._spec_stream_task = None
continue
# debounce small updates
await asyncio.sleep(PARTIAL_DEBOUNCE)
async with self._partial_lock:
current = self._partial
# if still same meaningful partial, start speculative LLM stream
if current and len(current.strip()) >= MIN_PARTIAL_CHARS:
# cancel previous speculative stream if running
if self._spec_stream_task:
self._spec_stream_task.cancel()
temp_ctx = chat_ctx.clone()
temp_ctx.add_message(role="user", content=current + " [PARTIAL]")
async def run_spec():
try:
async for chunk in llm.chat(temp_ctx, stream=True):
# send token chunk to clients / TTS immediately
await self.emit_assistant_chunk(chunk)
except asyncio.CancelledError:
# speculative run cancelled on finalization
return
self._spec_stream_task = asyncio.create_task(run_spec())
# llm_node: final authoritative LLM response on finalized chat context
async def llm_node(
self,
chat_ctx: ChatContext,
tools,
model_settings: agents.ModelSettings,
):
# cancel any speculative stream before final LLM call
if self._spec_stream_task:
self._spec_stream_task.cancel()
self._spec_stream_task = None
llm = openai.LLM(model="gpt-5.1")
async for chunk in llm.chat(chat_ctx, stream=True):
yield chunk
# helper: emit assistant chunk (implement per your output channel)
async def emit_assistant_chunk(self, chunk):
# Example: forward to connected clients or TTS node
# Implement actual emission depending on your infra
pass
Key points and behavior
• Speechmatics must run with enable_partials=True so INTERIM_TRANSCRIPT events arrive.
• The STT node updates a shared partial buffer and signals a background speculative loop.
• The speculative loop debounces partials (PARTIAL_DEBOUNCE) and only fires if partial length >= MIN_PARTIAL_CHARS to avoid noisy calls.
• Speculative LLM streams are cancelable; on FINAL_TRANSCRIPT we add the authoritative user message to chat and the llm_node does the final streaming response (and cancels speculative streams).
• Implement emit_assistant_chunk to forward token chunks to your clients or TTS pipeline.
• Tune PARTIAL_DEBOUNCE and MIN_PARTIAL_CHARS for your UX tradeoff (lower = faster but noisier).
If you want, I can:
• produce a one-file runnable example that wires real LiveKit audio tracks and a sample frontend emitter, or
• reduce this to an AgentSession preset that achieves similar behavior without code (less granular control). Sources: Speechmatics STT plugin guide | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs | Realtime model plugins | LiveKit Docs | OpenAI and LiveKit partner to turn Advanced Voice into an APInarrow-pager-84057
11/29/2025, 9:24 AMtall-airline-16756
11/29/2025, 9:24 AMfrom livekit.agents import AgentSession
from livekit.plugins.turn_detector.multilingual import MultilingualModel
session = AgentSession(
stt="speechmatics/stt:en", # streaming STT (interim partials)
llm="openai/gpt-5.1", # streaming-capable LLM
tts=None, # optional
vad=None, # let STT handle VAD/partials
turn_detection=MultilingualModel(), # semantic EOU detection for faster commits
preemptive_generation=True, # begin LLM work on partials
voice_options={
"partial_debounce_ms": 250, # debounce partial updates (tune 150–500ms)
"min_partial_chars": 12, # avoid tiny partial triggers
},
)
Node.js (minimal):
import { AgentSession } from "@livekit/agents";
import { MultilingualModel } from "@livekit/turn-detector";
const session = new AgentSession({
stt: "speechmatics/stt:en",
llm: "openai/gpt-5.1",
tts: undefined,
vad: undefined,
turnDetection: new MultilingualModel(),
preemptiveGeneration: true,
voiceOptions: {
partialDebounceMs: 250,
minPartialChars: 12,
},
});
Tuning notes (short):
• Set partial_debounce_ms lower for faster reactions (150–250ms) or higher to reduce noise.
• Lower min_partial_chars to react to short commands; raise to avoid false triggers.
• If you need even lower latency, use a realtime model (audio→LLM) instead of STT→LLM.
Want this as a one-file runnable example wiring to a LiveKit room/audio track?narrow-pager-84057
11/29/2025, 9:29 AMtall-airline-16756
11/29/2025, 9:29 AMenable_partials=True (or use preset stt="speechmatics/stt:en").
2) Turn on preemptive partial generation
• Set preemptive_generation=True in AgentSession so LLM work starts on interim text.
3) Use semantic EOU (not long VAD silence)
• Use turn_detection=MultilingualModel() or LiveKit EOU model to avoid waiting for long silence.
4) Lower debounce and min-partial thresholds
• Set partial_debounce_ms to 150–300 and min_partial_chars to ~8–12 to ensure partials trigger LLM quickly.
5) Verify pipeline forwards INTERIM events
• If using a custom agent, ensure stt_node yields INTERIM_TRANSCRIPT events and updates chat context immediately (don’t only add messages on FINAL).
• If using AgentSession preset, verify your runtime actually receives interim events (check logs for INTERIM_TRANSCRIPT).
6) Stream-enable the LLM calls
• Use streaming chat (token-by-token) to observe early LLM outputs; ensure the LLM binding supports streaming and you’re consuming stream events immediately.
7) Avoid cancelling speculative runs too eagerly
• If you start speculative LLM streams on partials, don’t immediately cancel them on the next small partial; instead debounce/cancel only on final or large change.
8) Check client/network buffering
• Confirm your client/TTS path is not buffering output until silence. Logs on both the agent and LLM request/response times help spot where the 2–3s comes from.
Tool-call specific tips
• Detect tool intent early in partials (keyword/intent matcher) and trigger a preemptive tool call, then confirm/adjust when FINAL arrives.
• If tools are invoked via the LLM, ensure the LLM is allowed to emit tool-call intents on partial context (preemptive generation), and your tool executor accepts provisional calls (with reconcile on final).
Quick diagnostic info I need
1. Are you using the standard AgentSession preset or a custom Agent with `stt_node`/`llm_node` overrides?
2. Are INTERIM_TRANSCRIPT events appearing in your agent logs in real time (yes/no)?
If you want, tell me answers to those two and I’ll give a tiny config or code diff tuned to your setup (preset or custom) to eliminate the 2–3s pause.narrow-pager-84057
11/29/2025, 9:32 AM...
stt=speechmatics.STT(
enable_partials=True,
enable_diarization=True,
end_of_utterance_silence_trigger=0.3,
speaker_active_format="<{speaker_id}>{text}</{speaker_id}>",
),
llm=openai.LLM(model=xxx)tall-airline-16756
11/29/2025, 9:33 AMstt=speechmatics.STT(
enable_partials=True,
end_of_utterance_mode=speechmatics.EndOfUtteranceMode.NONE,
end_of_utterance_silence_trigger=0.3,
enable_diarization=True,
speaker_active_format="<{speaker_id}>{text}</{speaker_id}>",
)
• Use semantic turn detection and preemptive generation:
session = AgentSession(
stt=stt,
llm=openai.LLM(model="gpt-5.1"),
turn_detection=MultilingualModel(),
preemptive_generation=True,
voice_options={"partial_debounce_ms":250, "min_partial_chars":12},
)
2) If you still see pauses → lightweight override (minimal)
• Ensure INTERIM_TRANSCRIPT events are forwarded into the chat context as interim messages (not only on FINAL). Either:
◦ Use the AgentSession preset above (recommended), or
◦ Override stt_node to set a partial buffer and signal a background loop that starts a streaming LLM call on debounced partials (see earlier example I provided).
3) Tool-call tips
• Detect tool intent on partials (keyword/intent matcher) and trigger a speculative tool invocation; reconcile on FINAL.
• Don’t cancel speculative LLM/tool runs on every tiny partial — use debounce (150–300ms) and a min-char threshold.
4) Quick checks to confirm root cause
• Do you see INTERIM_TRANSCRIPT events in agent logs in real time? (yes/no)
• Are you using AgentSession preset (above) or a custom agent with `stt_node`/`llm_node` overrides?
Tell me those two answers and I’ll give the exact minimal change (one-line) or a tiny diff to your code to remove the 2–3s pause.
Sources: Speechmatics STT plugin guide | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs | Agent speech and audio | LiveKit docs | Turn detection and interruptions | LiveKit Docs | Text and transcriptions | LiveKit docsnarrow-pager-84057
11/29/2025, 9:36 AMtall-airline-16756
11/29/2025, 9:36 AM