Skip to main content

pipecat-facemode

FaceMode avatar output for Pipecat pipelines. The integration taps TTSAudioRawFrame, sends canonical 16-bit PCM to FaceMode, and converts the avatar's LiveKit or Daily room audio and video back into Pipecat output frames.

The package is intentionally a small FrameProcessor. It does not replace a Pipecat transport. Place it after a TTS service and before the output transport:

transport input -> STT -> LLM -> TTS -> FaceModeVideoService -> transport output

By default, source TTSAudioRawFrame objects are consumed. This prevents the source TTS audio and the avatar's returned audio from being played twice. Set forward_tts_audio=True only when the pipeline intentionally needs both.

Install

pip install pipecat-facemode

For Daily rooms, also install the Daily extra:

pip install "pipecat-facemode[daily]"

From this directory:

pip install .

The package requires Python 3.13 or later and supports pipecat-ai>=1.7,<2, livekit>=1.1,<2, daily-python>=0.31,<1 (optional), aiohttp>=3.10,<4, websockets>=14,<17, and numpy>=2,<3.

Basic usage

room.token is the server-side worker token sent to FaceMode. The separate subscriber_token (livekit_subscriber_token remains as a LiveKit-only alias) is used by this Pipecat process to subscribe to the room. Use separate participant identities and tokens in production.

import os

from pipecat.pipeline.pipeline import Pipeline
from pipecat.services.cartesia.tts import CartesiaTTSService
from pipecat_facemode import FaceModeVideoService


tts = CartesiaTTSService(
    api_key=os.environ["CARTESIA_API_KEY"],
    settings=CartesiaTTSService.Settings(
        voice="71a7ad14-091c-4e8e-a314-022ece01c121",
    ),
)

facemode = FaceModeVideoService(
    api_key=os.environ["FACEMODE_API_KEY"],
    avatar_id=os.environ.get("FACEMODE_AVATAR_ID", ""),
    room={
        "type": "livekit",
        "url": os.environ["LIVEKIT_URL"],
        "token": os.environ["LIVEKIT_WORKER_TOKEN"],
    },
    livekit_subscriber_token=os.environ["LIVEKIT_SUBSCRIBER_TOKEN"],
    room_name=os.environ["LIVEKIT_ROOM_NAME"],
    # Optional speech input provider persisted by the backend for the session:
    # deepgram, gemini, gnani, elevenlabs, openai, cartesia, sarvam, or custom.
    input_provider=os.environ.get("FACEMODE_INPUT_PROVIDER") or None,
)

pipeline = Pipeline([
    transport.input(),
    tts,
    facemode,
    transport.output(),
])

See examples/basic_pipeline.py for a complete pipeline using Pipecat's LiveKit transport. The same-room example disables the transport's audio and video outputs because the FaceMode worker already publishes both avatar tracks directly into that LiveKit room. It also uses distinct tokens for the FaceMode worker, Pipecat subscriber, Pipecat transport, and viewer.

Daily rooms

Daily rooms work the same way through room.type: "daily". The service joins the room with a receive-only daily-python CallClient, matches the FaceMode worker participant by its Daily userName (avatar_participant_identity, default facemode-avatar), and forwards the worker's camera and microphone renderer frames into the pipeline.

facemode = FaceModeVideoService(
    api_key=os.environ["FACEMODE_API_KEY"],
    avatar_id=os.environ.get("FACEMODE_AVATAR_ID", ""),
    room={
        "type": "daily",
        "url": os.environ["DAILY_ROOM_URL"],      # https://<domain>.daily.co/<room>
        "token": os.environ["DAILY_WORKER_TOKEN"], # meeting token for the worker
    },
    subscriber_token=os.environ["DAILY_SUBSCRIBER_TOKEN"],
    avatar_participant_identity="facemode-avatar",
)

See examples/daily_pipeline.py for a complete pipeline using Pipecat's DailyTransport. Daily support requires pip install "pipecat-facemode[daily]"; without it, configuring a Daily room raises FaceModeConfigurationError with install instructions.

FaceMode session and WebSocket protocol

On StartFrame, the service:

  1. Connects to the supplied room (livekit.rtc for LiveKit rooms, a receive-only daily-python CallClient for Daily rooms).

  2. Calls POST {api_url}/sessions with the room object (and inputProvider when input_provider is configured). The request never sends waitForIngestion; current backends reject it as an unknown field:

    {
      "avatarId": "avatar-id",
      "inputProvider": "deepgram",
      "room": {
        "type": "livekit",
        "url": "wss://project.livekit.cloud",
        "token": "server-side-token"
      }
    }
    

    A 201 response returns ingestion.ready: true with the worker WebSocket url and a one-time wsToken immediately.

  3. When the response has ingestion.ready: false, polls GET {api_url}/sessions/{id} using bounded backoff for up to 240 seconds until ready WebSocket credentials are available; FAILED or ENDED worker states stop the wait immediately. Room credentials from the initial response remain in memory and are not expected in the status response.

  4. Opens the returned WebSocket with the facemode.<ws-token> subprotocol, compression disabled, native keepalives disabled, a 240-second open timeout, and optional backend-provided ingestion.headers forwarded unchanged. This package requires websockets>=14, so it uses the additional_headers API and never falls back to an unaffinitized connection.

  5. Starts the receive task, sends canonical start from the pipeline StartFrame, and waits for a validated started response.

  6. Starts application keepalives only after negotiation succeeds, preserving the protocol requirement that start is the first application message. If no application pong arrives for two keepalive intervals, the service aborts the silent transport and runs its bounded reconnect flow.

Call await service.wait_for_avatar() when an application needs to wait for FaceMode's audio_ready event or the first room video frame before announcing that avatar media is available.

The canonical protocol messages are used as follows:

  • start negotiates audio_encoding: pcm_s16le, sample rate, and channel count.
  • start_utterance precedes the first binary audio chunk.
  • TTSAudioRawFrame.audio is sent as binary little-endian signed 16-bit PCM, with no JSON or base64 wrapper.
  • end_utterance follows a TTS stop frame or a short idle period.
  • cancel_utterance is sent for Pipecat interruption frames.
  • ping is sent periodically while the session is alive.
  • end_session is sent during graceful EndFrame or pipeline cleanup.

Automatic reconnect

If the canonical WebSocket drops after a session was fully started, the service reconnects without caller-visible pipeline failure:

  1. It calls POST {api_url}/sessions/{id}/reconnect with the original room object (plus the persisted inputProvider when configured). Every response mints a fresh one-time wsToken; tokens are never reused.
  2. It opens a new socket with the facemode.<new-token> subprotocol, resends the same start negotiation, and waits for started before audio resumes.
  3. At most 2 reconnect attempts run with bounded backoff. Recovery is single-flight, so simultaneous close/error notifications share one attempt.

Sequence numbers keep increasing across reconnects, an explicitly open utterance is re-declared on the new socket, and already-sent audio is never replayed. Sends that arrive during the gap wait for the new socket instead of failing. No reconnect is attempted on intentional shutdown (EndFrame, CancelFrame, stop, cleanup), on server-terminal states (session_ending, ended, fatal error messages), or before the session is fully started. When the reconnect budget is exhausted, the failure surfaces as a FaceModeProtocolError that never contains token or key material.

The service calls super().__init__() and super().process_frame(...), and forwards non-consumed frames with their original FrameDirection. Lifecycle and interruption frames are forwarded after the FaceMode action completes. Pipecat 1.7 exposes the interruption event as InterruptionFrame; releases that expose separate StartInterruptionFrame and StopInterruptionFrame classes are handled without changing the public service API.

LiveKit token grants

Keep all LiveKit and FaceMode credentials on the server. Never put them in browser code or log messages.

The token in room.token must identify the FaceMode worker participant and grant that participant:

  • room_join=True for the exact LIVEKIT_ROOM_NAME;
  • can_publish=True so the avatar can publish its audio and video tracks;
  • can_subscribe=True so the worker can join the room's media session; and
  • a stable, unique participant identity and name if your room policy requires it.

The separate livekit_subscriber_token used by FaceModeVideoService must identify the Pipecat subscriber and grant:

  • room_join=True for the same room; and
  • can_subscribe=True.

Grant subscriber publish permission only if the application needs it. A token with publish and subscribe grants can be reused for both connections, but sharing a participant identity between the FaceMode worker and Pipecat subscriber is not recommended because a LiveKit room permits only one participant for an identity.

Example server-side token generation with livekit-api:

from livekit import api

worker_token = (
    api.AccessToken()
    .with_identity("facemode-avatar")
    .with_name("FaceMode Avatar")
    .with_grants(
        api.VideoGrants(
            room_join=True,
            room=room_name,
            can_publish=True,
            can_subscribe=True,
        )
    )
    .to_jwt()
)

subscriber_token = (
    api.AccessToken()
    .with_identity("pipecat-facemode-subscriber")
    .with_name("Pipecat FaceMode Subscriber")
    .with_grants(
        api.VideoGrants(
            room_join=True,
            room=room_name,
            can_subscribe=True,
        )
    )
    .to_jwt()
)

The sample token code is for a backend only. The LiveKit API secret must never be sent to a client.

Daily meeting tokens

Keep all Daily and FaceMode credentials on the server. Never put them in browser code or log messages.

Daily meeting tokens are minted through the Daily REST API (POST /meeting-tokens). The token in room.token must identify the FaceMode worker participant:

  • properties.room_name set to the Daily room name in room.url;
  • properties.user_name set to the value the plugin filters on (avatar_participant_identity, default facemode-avatar); and
  • publish permissions for camera and microphone so the worker can publish avatar media (for example permissions.canSend: ["video", "audio"], or an owner token).

The separate subscriber_token used by FaceModeVideoService must identify the Pipecat subscriber with a different user_name (for example pipecat-facemode-subscriber) for the same room_name. Reusing the worker meeting token also works, but the subscriber then shares the avatar's user_name, which is not recommended.

import requests

worker_token = requests.post(
    "https://api.daily.co/v1/meeting-tokens",
    headers={"Authorization": f"Bearer {DAILY_API_KEY}"},
    json={
        "properties": {
            "room_name": room_name,
            "user_name": "facemode-avatar",
            "is_owner": True,
        }
    },
).json()["token"]

subscriber_token = requests.post(
    "https://api.daily.co/v1/meeting-tokens",
    headers={"Authorization": f"Bearer {DAILY_API_KEY}"},
    json={
        "properties": {
            "room_name": room_name,
            "user_name": "pipecat-facemode-subscriber",
        }
    },
).json()["token"]

The sample token code is for a backend only. The Daily API key must never be sent to a client.

Video frame compatibility

Pipecat 1.7 uses OutputImageRawFrame for output video. The package also checks for OutputVideoRawFrame and falls back to ImageRawFrame, so importing the package remains safe across Pipecat releases that use different output video class names. LiveKit video is requested as RGB24 when the SDK exposes that format; Daily video is requested as RGB (with an RGBA fallback) through set_video_renderer. Both are copied into NumPy-backed RGB or RGBA image frames.

Lifecycle and failure behavior

  • REST and WebSocket failures raise typed FaceMode exceptions without including API keys or token values in log messages; facemode. credential prefixes are redacted alongside Bearer material.
  • The ingestion-ready poll budget and the WebSocket open/handshake budget are each 240 seconds. The start/started acknowledgement uses protocol_timeout (default 15 seconds).
  • WebSocket receive, keepalive, audio, and video tasks are cancelled and awaited during EndFrame, cleanup, or a failed startup. Graceful shutdown sends end_session and waits up to three seconds for canonical ended before closing the socket.
  • ended is a WebSocket protocol acknowledgement, not proof that backend worker cleanup, provider cancellation, or billing finalization is complete. Callers that need backend cleanup confirmation poll the public session endpoint until it becomes terminal.
  • Room media published before the connection is discovered after startup (LiveKit track_subscribed and the initial room scan; Daily participants() scan plus on_participant_joined events). Media that appears later is handled automatically.
  • avatar_participant_identity defaults to facemode-avatar to avoid forwarding other remote participants. For LiveKit it matches the participant identity; for Daily it matches the participant userName from the worker meeting token. Set it to the identity or user name in the worker room token when that token uses a different value. The local subscriber media is always ignored.

License

Apache-2.0 - see LICENSE. Part of the facemode-integrations monorepo.

Metadata

Release files for pipecat-facemode 0.3.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pipecat-facemode 0.3.2
File Size Uploaded Provenance Actions
pipecat_facemode-0.3.2.tar.gz 54.7 kB Without provenance Details for pipecat_facemode-0.3.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pipecat-facemode 0.3.2
File Interpreter ABI Platform Actions
pipecat_facemode-0.3.2-py3-none-any.whl Python 3 none any Details for pipecat_facemode-0.3.2-py3-none-any.whl

Total release size: 91.3 kB

Release files / pipecat_facemode-0.3.2.tar.gz

Download URL pipecat_facemode-0.3.2.tar.gz
Size 54.7 kB
Tags Source
SHA-256 checksum
How to use checksums
fa5fcf6adea0d3b7bb9bddcf47e388170366a454b1b9d2e20a93182c0044b7d5
BLAKE2b-256 checksum
How to use checksums
b950d9f5b677c79b3509c2f93e0950cb9d0b941721080c4509b0a0382458872b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.6

Release files / pipecat_facemode-0.3.2-py3-none-any.whl

Download URL pipecat_facemode-0.3.2-py3-none-any.whl
Size 36.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
01d70138f9dae65271bb82f3af96f580e4d1c35d8420ec4e7963faac41ff8df3
BLAKE2b-256 checksum
How to use checksums
46abdfd5a5e2a6fc06374540196bddcc00f6ec4fe58e7b2d2c46f4876dafd297
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.6

Security for pipecat-facemode 0.3.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page