Is there any way we could use local speech to text...
# ask-ai
s
Is there any way we could use local speech to text and text to speech models with livekit?
t
Thanks for reaching out, Maaz. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Yes — you can use local STT and TTS models with LiveKit by creating custom Agents that run your models. What you can do: • Implement a custom STT node in an Agent to process audio frames with your local speech-to-text model and return transcripts. • Implement a custom TTS node in an Agent to convert text to audio using your local text-to-speech model. Options for connecting local models: • Run your model server locally and have the Agent call its API. • If the model supports a standard-compatible API (e.g., OpenAI-compatible), adapt an existing plugin or client inside the Agent. • Use the open-source Agents framework so all model execution can remain on your infrastructure (no cloud inference required). Would you like: • a short example of how an STT node receives audio frames and returns text, or • guidance on packaging a local TTS server and wiring it into an Agent? Sources: Speech-to-text (STT) models | LiveKit Docs
s
give me an example as well
t
Thanks — below is a concise, runnable Python example showing how to wire local STT and TTS into a LiveKit Agent by overriding the
stt_node
and
tts_node
. It uses placeholders where you’ll call your local model servers (Whisper/Vosk/etc. for STT, Coqui/Piper/etc. for TTS). Note: replace the placeholder functions with your model-specific calls.
Copy code
import asyncio
from typing import AsyncIterable, Optional
from livekit import rtc
from livekit.agents import Agent, AgentSession, ChatContext, ModelSettings, stt, tts

# Minimal AudioFrame-like dataclass if needed (replace with livekit.rtc.AudioFrame in real usage)
# from livekit.rtc import AudioFrame

class LocalAgent(Agent):
    def __init__(self):
        super().__init__(instructions="Agent using local STT/TTS")

    async def stt_node(
        self,
        audio: AsyncIterable[rtc.AudioFrame],
        model_settings: ModelSettings,
    ) -> Optional[AsyncIterable[stt.SpeechEvent]]:
        """
        Consume audio frames from LiveKit, send them to your local STT engine,
        and yield SpeechEvent(s). Replace run_local_stt with your implementation.
        """
        async def gen():
            buffer = bytearray()
            async for frame in audio:
                # collect raw audio bytes (frame.data) until you want to transcribe
                buffer.extend(frame.data)
                # example: call STT per frame or when buffer reaches a size/voice activity
                text = await self.run_local_stt(bytes(buffer))
                if text:
                    yield stt.SpeechEvent(
                        type=stt.SpeechEventType.FINAL_TRANSCRIPT,
                        alternatives=[stt.SpeechEventAlternative(text=text, confidence=0.9)]
                    )
                    buffer.clear()
        return gen()

    async def tts_node(
        self,
        text: AsyncIterable[str],
        model_settings: ModelSettings,
    ) -> AsyncIterable[rtc.AudioFrame]:
        """
        Receive text chunks and yield audio frames synthesized by your local TTS engine.
        Replace run_local_tts with your implementation that returns raw PCM or bytes.
        """
        async for segment in text:
            if not segment.strip():
                continue
            pcm_bytes, sample_rate = await self.run_local_tts(segment)
            # Convert PCM bytes into one or more AudioFrame objects expected by LiveKit
            # Here we yield a single frame for simplicity
            yield rtc.AudioFrame(
                data=pcm_bytes,
                sample_rate=sample_rate,
                num_channels=1,
                samples_per_channel=len(pcm_bytes) // 2,  # 16-bit PCM example
            )

    # -- Replace these with real local model calls --
    async def run_local_stt(self, pcm: bytes) -> str:
        """
        Example: call a local Whisper/Vosk/faster-whisper server or library.
        Return the transcribed text string.
        """
        # TODO: implement actual inference call
        await asyncio.sleep(0.01)
        return "transcribed text from local STT"

    async def run_local_tts(self, text: str) -> tuple[bytes, int]:
        """
        Example: call a local Coqui/Piper TTS server or library.
        Return (pcm_bytes, sample_rate).
        """
        # TODO: implement actual synthesis call
        await asyncio.sleep(0.01)
        fake_pcm = b"\x00\x00" * 16000  # 1 second of silence @16kHz 16-bit
        return fake_pcm, 16000

    async def llm_node(self, chat_ctx: ChatContext, tools, model_settings: ModelSettings):
        # simple static response; replace with local LLM if desired
        yield "Okay — speaking via local TTS now."

async def main():
    session = AgentSession(stt=None, tts=None, vad=None, llm=None)
    agent = LocalAgent()
    await session.start(agent=agent)

    # Example: trigger a reply that will go through tts_node
    handle = session.generate_reply("Say hello using local TTS")
    await handle.wait_for_playout()

if __name__ == "__main__":
    asyncio.run(main())
Would you like: • a Node.js example, or • a filled-in STT/TTS example using a specific local model (Whisper, Vosk, Coqui, Piper)? Sources: Pipeline nodes and hooks | LiveKit docs | An open source stack for real-time multimodal AI