gradio-app/fastrtc

The python library for real-time communication

FastRTC – Real‑time audio/video streams for Python

FastRTC is a Python library that turns any function into a live audio or video stream that can be accessed over WebRTC, WebSockets, or even a telephone line. It is built on top of Gradio and FastAPI, letting you prototype or ship real‑time conversational agents (e.g., voice‑enabled ChatGPT, Gemini, Claude) with just a few lines of code.


Why it matters

  • Voice‑first AI apps – Hook up speech‑to‑text, LLM back‑ends, and text‑to‑speech in a single pipeline.
  • Zero‑config UI – stream.ui.launch() gives you a ready‑made web interface for testing and sharing.
  • Production ready – Mount the stream on an existing FastAPI service, expose a WebRTC endpoint, or serve a pure WebSocket feed.
  • Phone access – stream.fastphone() provisions a temporary phone number (via Hugging Face) so users can call into the app.

Quick start (audio echo)

from fastrtc import Stream, ReplyOnPause
import numpy as np

# Echo back whatever the user says until they pause.
def echo(audio: tuple[int, np.ndarray]):
    yield audio

stream = Stream(
    handler=ReplyOnPause(echo),   # pauses trigger a new turn
    modality="audio",
    mode="send-receive",
)

# Choose one of the launch options below
stream.ui.launch()          # opens a Gradio UI in the browser
# or
# stream.fastphone()       # get a phone number to call in
# or
# from fastapi import FastAPI
# app = FastAPI()
# stream.mount(app)        # expose /rtc endpoint for your own frontend

Core concepts

Concept What it does
Stream The central object that wires a user‑provided handler to a real‑time transport (WebRTC, WebSocket, phone).
handler A callable that receives the incoming media (audio tuple or video frame) and yields the response media.
ReplyOnPause Convenience wrapper that buffers audio until the user stops speaking, then calls the handler – perfect for turn‑taking chat.
ui.launch() Spins up a Gradio UI that automatically handles the WebRTC handshake and displays the stream.
mount(app) Registers the stream on a FastAPI app (/rtc for WebRTC, /ws for WebSocket) so you can embed it in any backend.
fastphone() Requests a temporary phone number (requires a Hugging Face token) and routes the call into the same audio pipeline.

Feature highlights

  • Automatic voice activity detection (VAD) – optional fastrtc[vad] extra adds built‑in pause detection.
  • Text‑to‑speech integration – optional fastrtc[tts] extra bundles helpers for streaming TTS back to the user.
  • Custom UI – While the default Gradio UI is ready‑to‑go, you can supply your own frontend by mounting the stream on FastAPI.
  • Multi‑modal support – Works with modality="audio" or "video"; you can even mix additional Gradio inputs (e.g., sliders) for parameter control.
  • Demo gallery – The README links to a set of Hugging Face Spaces demos (Gemini audio‑video chat, OpenAI voice, Whisper transcription, YOLOv10 object detection, etc.) that showcase real‑world use cases.

Installation

pip install fastrtc                     # core library
pip install "fastrtc[vad,tts]"          # optional VAD and TTS support

Typical workflow

  1. Define a handler – a function that receives media and yields a response (audio tuple or video frame).
  2. Wrap with ReplyOnPause (optional) if you need turn‑taking.
  3. Create a Stream specifying modality, mode, and any extra Gradio inputs.
  4. Launch via .ui.launch(), .fastphone(), or mount on FastAPI.

Example: LLM‑powered voice assistant

from fastrtc import Stream, ReplyOnPause, audio_to_bytes, aggregate_bytes_to_16bit
import numpy as np, gradio as gr
from groq import Groq
from anthropic import Anthropic
from elevenlabs import ElevenLabs

# clients for transcription, LLM, and TTS
groq = Groq()
claude = Anthropic()
tts = ElevenLabs()

def respond(audio):
    # 1️⃣ Transcribe spoken input
    transcript = groq.audio.transcriptions.create(
        file=("audio.mp3", audio_to_bytes(audio)),
        model="whisper-large-v3-turbo",
        response_format="verbose_json",
    ).text

    # 2️⃣ Send to LLM (Claude in this case)
    reply = claude.messages.create(
        model="claude-3-5-haiku-20241022",
        max_tokens=512,
        messages=[{"role": "user", "content": transcript}],
    ).content
    reply_text = " ".join(b.text for b in reply if getattr(b, "type", None) == "text")

    # 3️⃣ Stream TTS back to the user
    tts_stream = tts.text_to_speech.convert_as_stream(
        text=reply_text,
        voice_id="JBFqnCBsd6RMkjVDRZzb",
        model_id="eleven_multilingual_v2",
        output_format="pcm_24000",
    )
    for chunk in aggregate_bytes_to_16bit(tts_stream):
        audio_arr = np.frombuffer(chunk, dtype=np.int16).reshape(1, -1)
        yield (24000, audio_arr)

stream = Stream(
    modality="audio",
    mode="send-receive",
    handler=ReplyOnPause(respond),
)
stream.ui.launch()

This snippet shows the full round‑trip: speech → transcription → LLM → TTS → speech.


Where to go next?

  • Read the full user guide – https://fastrtc.org
  • Browse the cookbook – https://fastrtc.org/cookbook/ for ready‑made patterns (object detection, code editing, etc.)
  • Deploy – mount on a FastAPI service behind a reverse proxy, or embed the WebRTC endpoint in a custom web app.
  • Experiment with phones – stream.fastphone() lets you test voice‑only flows without a webcam.

FastRTC bridges the gap between Python functions and real‑time interactive media, making it straightforward to build voice‑first AI agents, live video demos, or any application that needs low‑latency streaming of audio/video data.

Related

  • Project
  • Project
  • Project
  • Project