Pipecat Tutorial: Building Voice AI Agents with Python

# Tutorial Pipecat: Membangun Voice AI Agent dengan Python ## Pendahuluan Pipecat adalah framework open-source berbasis Python yang dirancang khusus untuk membangun aplikasi voice dan multimodal AI...

By Ruby Abdullah · · tutorial
PipecatVoice AIReal-time AIPythonConversational AI

Pipecat Tutorial: Building Voice AI Agents with Python

Introduction

Pipecat is an open-source Python framework specifically designed for building real-time voice and multimodal AI agent applications. Developed by the Daily.co team, Pipecat simplifies the complex process of building conversational AI by connecting various Speech-to-Text (STT), Large Language Model (LLM), and Text-to-Speech (TTS) services in an efficient pipeline.

In today's rapidly evolving AI landscape, voice AI agents have become one of the most sought-after applications. From automated customer service, virtual assistants, to healthcare applications requiring voice interaction — all need reliable infrastructure for processing audio in real-time. Pipecat addresses this need with a modular, easily customizable pipeline architecture.

This tutorial will guide you from basic installation to building a complete voice AI agent, including integration with various STT, LLM, and TTS providers, and deployment to production.

Why Pipecat?

Before diving into implementation, let's understand why Pipecat is an excellent choice for building voice AI agents:

  • Modular Pipeline Architecture: Each component (STT, LLM, TTS) is a module that can be replaced and combined as needed
  • Real-time Processing: Optimized for low latency, essential for natural conversations
  • Transport Agnostic: Supports various transport layers such as Daily, WebSocket, and local audio
  • Frame-based Architecture: Uses the concept of "frames" to efficiently stream data between components
  • Wide Integration Ecosystem: Supports OpenAI, Anthropic, Google, ElevenLabs, Deepgram, Whisper, and many more
  • Open Source: BSD-2 license, free to use for commercial projects
  • Installation

    System Requirements

    • Python 3.10 or later
    • pip or uv as package manager
    • FFmpeg (for audio processing)
    • PortAudio (for local audio I/O)

    Basic Installation

    # Install Pipecat core
    

    pip install pipecat-ai

    Install with all dependencies

    pip install "pipecat-ai[all]"

    Per-Provider Installation

    Pipecat uses an extras system to install dependencies based on the providers you need:

    # STT providers
    

    pip install "pipecat-ai[deepgram]" # Deepgram STT

    pip install "pipecat-ai[whisper]" # OpenAI Whisper

    pip install "pipecat-ai[google]" # Google Cloud STT

    pip install "pipecat-ai[azure]" # Azure Speech

    LLM providers

    pip install "pipecat-ai[openai]" # OpenAI GPT

    pip install "pipecat-ai[anthropic]" # Anthropic Claude

    pip install "pipecat-ai[google]" # Google Gemini

    TTS providers

    pip install "pipecat-ai[elevenlabs]" # ElevenLabs

    pip install "pipecat-ai[cartesia]" # Cartesia Sonic

    pip install "pipecat-ai[playht]" # PlayHT

    pip install "pipecat-ai[xtts]" # Coqui XTTS

    Transport

    pip install "pipecat-ai[daily]" # Daily.co WebRTC

    pip install "pipecat-ai[websocket]" # WebSocket

    pip install "pipecat-ai[local]" # Local audio

    Combined Installation

    For common scenarios, you can install multiple extras at once:

    # Common setup: Deepgram STT + OpenAI LLM + ElevenLabs TTS + Daily transport
    

    pip install "pipecat-ai[deepgram,openai,elevenlabs,daily]"

    Local development setup

    pip install "pipecat-ai[whisper,openai,cartesia,local]"

    Installing FFmpeg and PortAudio

    # Ubuntu/Debian
    

    sudo apt-get install ffmpeg portaudio19-dev

    macOS

    brew install ffmpeg portaudio

    Windows (using Chocolatey)

    choco install ffmpeg

    Verify Installation

    import pipecat
    

    print(f"Pipecat version: {pipecat.version}")

    Check module availability

    from pipecat.pipeline.pipeline import Pipeline

    from pipecat.pipeline.runner import PipelineRunner

    from pipecat.pipeline.task import PipelineTask

    print("Core modules loaded successfully!")

    Core Concepts

    Frame Architecture

    Pipecat uses the concept of Frames as the fundamental data unit flowing through the pipeline. Each frame carries a specific data type:

    from pipecat.frames.frames import (
    

    AudioRawFrame, # Raw audio data

    TextFrame, # Plain text

    TranscriptionFrame, # STT transcription result

    LLMMessagesFrame, # Messages for LLM

    TTSAudioRawFrame, # TTS audio output

    EndFrame, # Pipeline end signal

    UserStartedSpeakingFrame, # User started speaking

    UserStoppedSpeakingFrame, # User stopped speaking

    )

    Pipeline and Processors

    A Pipeline is a chain of processors that process frames sequentially:

    from pipecat.pipeline.pipeline import Pipeline
    

    from pipecat.pipeline.runner import PipelineRunner

    from pipecat.pipeline.task import PipelineTask, PipelineParams

    Create a simple pipeline

    pipeline = Pipeline([

    transport.input(), # Receive audio from user

    sttservice, # Convert speech to text

    llmservice, # Process text with LLM

    ttsservice, # Convert response to speech

    transport.output(), # Send audio to user

    ])

    Custom FrameProcessor

    You can create your own processors to handle custom logic:

    from pipecat.processors.frameprocessor import FrameProcessor
    

    from pipecat.frames.frames import Frame, TextFrame

    class TextLoggerProcessor(FrameProcessor):

    """Processor that logs all TextFrames passing through."""

    async def processframe(self, frame: Frame, direction):

    await super().processframe(frame, direction)

    if isinstance(frame, TextFrame):

    print(f"[LOG] Text: {frame.text}")

    # Forward frame to the next processor

    await self.pushframe(frame, direction)

    Basic Usage: Simple Voice Bot

    Let's build your first voice bot that can answer questions in real-time.

    Setup Environment Variables

    # .env file
    

    OPENAIAPIKEY=sk-your-openai-key

    DEEPGRAMAPIKEY=your-deepgram-key

    ELEVENLABSAPIKEY=your-elevenlabs-key

    DAILYAPIKEY=your-daily-api-key

    Voice Bot with Local Audio

    import asyncio
    

    import os

    from dotenv import loaddotenv

    from pipecat.pipeline.pipeline import Pipeline

    from pipecat.pipeline.runner import PipelineRunner

    from pipecat.pipeline.task import PipelineTask, PipelineParams

    from pipecat.services.openai.llm import OpenAILLMService

    from pipecat.services.deepgram.stt import DeepgramSTTService

    from pipecat.services.elevenlabs.tts import ElevenLabsTTSService

    from pipecat.transports.local.audio import LocalAudioTransport

    loaddotenv()

    async def main():

    # Configure local transport (microphone and speaker)

    transport = LocalAudioTransport(

    micenabled=True,

    speakerenabled=True,

    micsamplerate=16000,

    speakersamplerate=24000,

    )

    # Configure Speech-to-Text (Deepgram)

    stt = DeepgramSTTService(

    apikey=os.getenv("DEEPGRAMAPIKEY"),

    language="en",

    )

    # Configure LLM (OpenAI)

    llm = OpenAILLMService(

    apikey=os.getenv("OPENAIAPIKEY"),

    model="gpt-4o",

    systemprompt="""You are a friendly and helpful AI assistant.

    Answer concisely in 2-3 sentences per response.""",

    )

    # Configure Text-to-Speech (ElevenLabs)

    tts = ElevenLabsTTSService(

    apikey=os.getenv("ELEVENLABSAPIKEY"),

    voiceid="21m00Tcm4TlvDq8ikWAM", # Rachel voice

    model="elevenmultilingualv2",

    )

    # Build pipeline

    pipeline = Pipeline([

    transport.input(),

    stt,

    llm,

    tts,

    transport.output(),

    ])

    # Run pipeline

    task = PipelineTask(

    pipeline,

    params=PipelineParams(

    allowinterruptions=True,

    enablemetrics=True,

    ),

    )

    runner = PipelineRunner()

    await runner.run(task)

    if name == "main":

    asyncio.run(main())

    Voice Bot with Daily WebRTC

    For web-based deployment, use Daily as the transport layer:

    import asyncio
    

    import os

    from dotenv import loaddotenv

    from pipecat.pipeline.pipeline import Pipeline

    from pipecat.pipeline.runner import PipelineRunner

    from pipecat.pipeline.task import PipelineTask, PipelineParams

    from pipecat.services.openai.llm import OpenAILLMService

    from pipecat.services.deepgram.stt import DeepgramSTTService

    from pipecat.services.cartesia.tts import CartesiaTTSService

    from pipecat.transports.services.daily import DailyTransport, DailyParams

    loaddotenv()

    async def main():

    # Configure Daily transport

    transport = DailyTransport(

    roomurl=os.getenv("DAILYROOMURL"),

    token=os.getenv("DAILYTOKEN"),

    botname="AI Assistant",

    params=DailyParams(

    audioinenabled=True,

    audiooutenabled=True,

    vadenabled=True, # Voice Activity Detection

    vadaudiopassthrough=True,

    ),

    )

    # STT Service

    stt = DeepgramSTTService(

    apikey=os.getenv("DEEPGRAMAPIKEY"),

    )

    # LLM Service

    llm = OpenAILLMService(

    apikey=os.getenv("OPENAIAPIKEY"),

    model="gpt-4o",

    systemprompt="You are a helpful assistant. Keep responses brief.",

    )

    # TTS Service (Cartesia - low latency)

    tts = CartesiaTTSService(

    apikey=os.getenv("CARTESIAAPIKEY"),

    voiceid="a0e99841-438c-4a64-b679-ae501e7d6091",

    model="sonic-english",

    samplerate=24000,

    )

    # Pipeline

    pipeline = Pipeline([

    transport.input(),

    stt,

    llm,

    tts,

    transport.output(),

    ])

    task = PipelineTask(

    pipeline,

    params=PipelineParams(

    allowinterruptions=True,

    ),

    )

    # Event handlers

    @transport.eventhandler("onfirstparticipantjoined")

    async def onfirstparticipantjoined(transport, participant):

    print(f"Participant joined: {participant['id']}")

    await task.queueframes([

    TextFrame("Hello! I'm your AI assistant. How can I help you?")

    ])

    @transport.eventhandler("onparticipantleft")

    async def onparticipantleft(transport, participant, reason):

    print(f"Participant left: {participant['id']}")

    await task.queueframes([EndFrame()])

    runner = PipelineRunner()

    await runner.run(task)

    if name == "main":

    asyncio.run(main())

    Advanced Usage

    1. Function Calling with Voice Bot

    Integrate function calling to give your voice bot action capabilities:

    import asyncio
    

    import os

    import json

    from datetime import datetime

    from dotenv import loaddotenv

    from pipecat.pipeline.pipeline import Pipeline

    from pipecat.pipeline.runner import PipelineRunner

    from pipecat.pipeline.task import PipelineTask, PipelineParams

    from pipecat.services.openai.llm import OpenAILLMService

    from pipecat.services.deepgram.stt import DeepgramSTTService

    from pipecat.services.elevenlabs.tts import ElevenLabsTTSService

    from pipecat.transports.local.audio import LocalAudioTransport

    loaddotenv()

    Define tools/functions

    tools = [

    {

    "type": "function",

    "function": {

    "name": "getweather",

    "description": "Get weather information for a specific city",

    "parameters": {

    "type": "object",

    "properties": {

    "city": {

    "type": "string",

    "description": "City name, e.g., New York, London"

    }

    },

    "required": ["city"]

    }

    }

    },

    {

    "type": "function",

    "function": {

    "name": "gettime",

    "description": "Get the current time",

    "parameters": {

    "type": "object",

    "properties": {}

    }

    }

    },

    {

    "type": "function",

    "function": {

    "name": "setreminder",

    "description": "Set a reminder for the user",

    "parameters": {

    "type": "object",

    "properties": {

    "message": {

    "type": "string",

    "description": "Reminder message"

    },

    "minutes": {

    "type": "integer",

    "description": "Minutes from now"

    }

    },

    "required": ["message", "minutes"]

    }

    }

    }

    ]

    Implement function handlers

    async def handlegetweather(city: str) -> str:

    weatherdata = {

    "New York": {"temp": 22, "condition": "Cloudy", "humidity": 65},

    "London": {"temp": 18, "condition": "Rainy", "humidity": 80},

    "Tokyo": {"temp": 28, "condition": "Sunny", "humidity": 55},

    }

    data = weatherdata.get(city, {"temp": 25, "condition": "Unknown", "humidity": 60})

    return json.dumps({

    "city": city,

    "temperature": data["temp"],

    "condition": data["condition"],

    "humidity": data["humidity"]

    })

    async def handlegettime() -> str:

    now = datetime.now()

    return json.dumps({

    "time": now.strftime("%H:%M"),

    "date": now.strftime("%B %d, %Y")

    })

    async def handlesetreminder(message: str, minutes: int) -> str:

    return json.dumps({

    "status": "success",

    "message": f"Reminder '{message}' set for {minutes} minutes from now"

    })

    Function dispatcher

    async def functionhandler(functionname: str, toolcallid: str, arguments: dict, llm: OpenAILLMService):

    result = None

    if functionname == "getweather":

    result = await handlegetweather(arguments["city"])

    elif functionname == "gettime":

    result = await handlegettime()

    elif functionname == "setreminder":

    result = await handlesetreminder(arguments["message"], arguments["minutes"])

    if result:

    await llm.processfunctionresult(toolcallid, result)

    async def main():

    transport = LocalAudioTransport(

    micenabled=True,

    speakerenabled=True,

    )

    stt = DeepgramSTTService(

    apikey=os.getenv("DEEPGRAMAPIKEY"),

    )

    llm = OpenAILLMService(

    apikey=os.getenv("OPENAIAPIKEY"),

    model="gpt-4o",

    systemprompt="""You are an AI assistant that can help with weather,

    time, and reminders. Use function calling when needed.""",

    tools=tools,

    )

    # Register function handlers

    llm.registerfunctionhandler("getweather", functionhandler)

    llm.registerfunctionhandler("gettime", functionhandler)

    llm.registerfunctionhandler("setreminder", functionhandler)

    tts = ElevenLabsTTSService(

    apikey=os.getenv("ELEVENLABSAPIKEY"),

    voiceid="21m00Tcm4TlvDq8ikWAM",

    )

    pipeline = Pipeline([

    transport.input(),

    stt,

    llm,

    tts,

    transport.output(),

    ])

    task = PipelineTask(

    pipeline,

    params=PipelineParams(allowinterruptions=True),

    )

    runner = PipelineRunner()

    await runner.run(task)

    if name == "main":

    asyncio.run(main())

    2. Conversation Context and Memory

    Manage conversation context for a more natural experience:

    from pipecat.processors.frameprocessor import FrameProcessor
    

    from pipecat.frames.frames import Frame, TranscriptionFrame, TextFrame

    class ConversationMemory(FrameProcessor):

    """Stores conversation history and provides context."""

    def init(self, maxturns: int = 10):

    super().init()

    self.history = []

    self.maxturns = maxturns

    async def processframe(self, frame: Frame, direction):

    await super().processframe(frame, direction)

    if isinstance(frame, TranscriptionFrame):

    self.history.append({

    "role": "user",

    "content": frame.text

    })

    self.trimhistory()

    elif isinstance(frame, TextFrame):

    self.history.append({

    "role": "assistant",

    "content": frame.text

    })

    self.trimhistory()

    await self.pushframe(frame, direction)

    def trimhistory(self):

    if len(self.history) > self.maxturns 2:

    self.history = self.history[-(self.maxturns 2):]

    def getcontext(self) -> list:

    return self.history.copy()

    3. Multi-Modal: Voice + Vision

    Integrate vision capabilities to process images alongside audio:

    import asyncio
    

    import os

    import base64

    from dotenv import loaddotenv

    from pipecat.pipeline.pipeline import Pipeline

    from pipecat.pipeline.runner import PipelineRunner

    from pipecat.pipeline.task import PipelineTask, PipelineParams

    from pipecat.services.openai.llm import OpenAILLMService

    from pipecat.services.deepgram.stt import DeepgramSTTService

    from pipecat.services.elevenlabs.tts import ElevenLabsTTSService

    from pipecat.transports.services.daily import DailyTransport, DailyParams

    from pipecat.processors.frameprocessor import FrameProcessor

    from pipecat.frames.frames import Frame, ImageRawFrame, TextFrame

    loaddotenv()

    class VisionProcessor(FrameProcessor):

    """Processes image frames and sends them to LLM for analysis."""

    def init(self, llmservice: OpenAILLMService):

    super().init()

    self.llm = llmservice

    self.lastimage = None

    async def processframe(self, frame: Frame, direction):

    await super().processframe(frame, direction)

    if isinstance(frame, ImageRawFrame):

    self.lastimage = frame

    imageb64 = base64.b64encode(frame.image).decode("utf-8")

    messages = [

    {

    "role": "user",

    "content": [

    {

    "type": "imageurl",

    "imageurl": {

    "url": f"data:image/jpeg;base64,{imageb64}"

    }

    },

    {

    "type": "text",

    "text": "Describe what you see in this image."

    }

    ]

    }

    ]

    await self.llm.processmessages(messages)

    else:

    await self.pushframe(frame, direction)

    async def main():

    transport = DailyTransport(

    roomurl=os.getenv("DAILYROOMURL"),

    token=os.getenv("DAILYTOKEN"),

    botname="Vision Bot",

    params=DailyParams(

    audioinenabled=True,

    audiooutenabled=True,

    camerainenabled=True,

    vadenabled=True,

    ),

    )

    stt = DeepgramSTTService(apikey=os.getenv("DEEPGRAMAPIKEY"))

    llm = OpenAILLMService(

    apikey=os.getenv("OPENAIAPIKEY"),

    model="gpt-4o",

    systemprompt="You can see and hear. Describe what you see when asked.",

    )

    tts = ElevenLabsTTSService(

    apikey=os.getenv("ELEVENLABSAPIKEY"),

    voiceid="21m00Tcm4TlvDq8ikWAM",

    )

    vision = VisionProcessor(llm)

    pipeline = Pipeline([

    transport.input(),

    stt,

    vision,

    llm,

    tts,

    transport.output(),

    ])

    task = PipelineTask(pipeline, params=PipelineParams(allowinterruptions=True))

    runner = PipelineRunner()

    await runner.run(task)

    if name == "main":

    asyncio.run(main())

    4. Smart Interrupt Handling

    Handle user interruptions while the bot is speaking:

    from pipecat.pipeline.task import PipelineParams
    
    

    params = PipelineParams(

    allowinterruptions=True,

    enablemetrics=True,

    reportonlyinitialttfb=True,

    )

    class SmartInterruptHandler(FrameProcessor):

    """Handler that detects and responds to user interruptions intelligently."""

    def init(self):

    super().init()

    self.isspeaking = False

    self.wasinterrupted = False

    async def processframe(self, frame: Frame, direction):

    await super().processframe(frame, direction)

    from pipecat.frames.frames import (

    BotStartedSpeakingFrame,

    BotStoppedSpeakingFrame,

    UserStartedSpeakingFrame,

    )

    if isinstance(frame, BotStartedSpeakingFrame):

    self.isspeaking = True

    elif isinstance(frame, BotStoppedSpeakingFrame):

    self.isspeaking = False

    self.wasinterrupted = False

    elif isinstance(frame, UserStartedSpeakingFrame):

    if self.isspeaking:

    self.wasinterrupted = True

    print("[INFO] User interrupted bot speech")

    await self.pushframe(frame, direction)

    5. Metrics and Monitoring

    Monitor your pipeline performance:

    from pipecat.processors.frameprocessor import FrameProcessor
    

    from pipecat.frames.frames import Frame, MetricsFrame

    class MetricsCollector(FrameProcessor):

    """Collects pipeline performance metrics."""

    def init(self):

    super().init()

    self.metrics = {

    "totalframes": 0,

    "sttlatency": [],

    "llmlatency": [],

    "ttslatency": [],

    "totalconversations": 0,

    }

    async def processframe(self, frame: Frame, direction):

    await super().processframe(frame, direction)

    self.metrics["totalframes"] += 1

    if isinstance(frame, MetricsFrame):

    for metric in frame.metrics:

    if "stt" in metric.name.lower():

    self.metrics["sttlatency"].append(metric.value)

    elif "llm" in metric.name.lower():

    self.metrics["llmlatency"].append(metric.value)

    elif "tts" in metric.name.lower():

    self.metrics["ttslatency"].append(metric.value)

    self.logmetrics()

    await self.pushframe(frame, direction)

    def logmetrics(self):

    for key in ["sttlatency", "llmlatency", "ttslatency"]:

    values = self.metrics[key]

    if values:

    avg = sum(values) / len(values)

    print(f"[METRICS] {key}: avg={avg:.0f}ms, "

    f"min={min(values):.0f}ms, max={max(values):.0f}ms")

    def getsummary(self) -> dict:

    summary = {"totalframes": self.metrics["totalframes"]}

    for key in ["sttlatency", "llmlatency", "ttslatency"]:

    values = self.metrics[key]

    if values:

    summary[key] = {

    "avg": sum(values) / len(values),

    "min": min(values),

    "max": max(values),

    "count": len(values),

    }

    return summary

    6. WebSocket Transport for Web Integration

    import asyncio
    

    import os

    from dotenv import loaddotenv

    from pipecat.pipeline.pipeline import Pipeline

    from pipecat.pipeline.runner import PipelineRunner

    from pipecat.pipeline.task import PipelineTask, PipelineParams

    from pipecat.services.openai.llm import OpenAILLMService

    from pipecat.services.deepgram.stt import DeepgramSTTService

    from pipecat.services.cartesia.tts import CartesiaTTSService

    from pipecat.transports.network.websocketserver import (

    WebSocketServerTransport,

    WebSocketServerParams,

    )

    loaddotenv()

    async def main():

    transport = WebSocketServerTransport(

    params=WebSocketServerParams(

    host="0.0.0.0",

    port=8765,

    audioinenabled=True,

    audiooutenabled=True,

    )

    )

    stt = DeepgramSTTService(apikey=os.getenv("DEEPGRAMAPIKEY"))

    llm = OpenAILLMService(

    apikey=os.getenv("OPENAIAPIKEY"),

    model="gpt-4o-mini",

    systemprompt="You are a helpful voice assistant. Keep responses concise.",

    )

    tts = CartesiaTTSService(

    apikey=os.getenv("CARTESIAAPIKEY"),

    voiceid="a0e99841-438c-4a64-b679-ae501e7d6091",

    )

    pipeline = Pipeline([

    transport.input(),

    stt,

    llm,

    tts,

    transport.output(),

    ])

    task = PipelineTask(

    pipeline,

    params=PipelineParams(allowinterruptions=True),

    )

    runner = PipelineRunner()

    print("WebSocket server running on ws://localhost:8765")

    await runner.run(task)

    if name == "main":

    asyncio.run(main())

    Client-side JavaScript to connect:

    // web-client.js
    

    const socket = new WebSocket("ws://localhost:8765");

    const audioContext = new AudioContext({ sampleRate: 24000 });

    socket.onopen = () => {

    console.log("Connected to Pipecat server");

    startAudioCapture();

    };

    socket.onmessage = async (event) => {

    if (event.data instanceof Blob) {

    const arrayBuffer = await event.data.arrayBuffer();

    const audioData = new Float32Array(arrayBuffer);

    playAudio(audioData);

    }

    };

    async function startAudioCapture() {

    const stream = await navigator.mediaDevices.getUserMedia({

    audio: {

    sampleRate: 16000,

    channelCount: 1,

    echoCancellation: true,

    noiseSuppression: true,

    }

    });

    const source = audioContext.createMediaStreamSource(stream);

    const processor = audioContext.createScriptProcessor(4096, 1, 1);

    processor.onaudioprocess = (e) => {

    const inputData = e.inputBuffer.getChannelData(0);

    const pcmData = new Int16Array(inputData.length);

    for (let i = 0; i < inputData.length; i++) {

    pcmData[i] = Math.max(-32768, Math.min(32767,

    Math.floor(inputData[i] * 32768)));

    }

    if (socket.readyState === WebSocket.OPEN) {

    socket.send(pcmData.buffer);

    }

    };

    source.connect(processor);

    processor.connect(audioContext.destination);

    }

    function playAudio(audioData) {

    const buffer = audioContext.createBuffer(1, audioData.length, 24000);

    buffer.getChannelData(0).set(audioData);

    const source = audioContext.createBufferSource();

    source.buffer = buffer;

    source.connect(audioContext.destination);

    source.start();

    }

    Deployment with FastAPI

    For production, integrate Pipecat with FastAPI:

    import asyncio
    

    import os

    from contextlib import asynccontextmanager

    from dotenv import loaddotenv

    from fastapi import FastAPI, WebSocket

    from fastapi.responses import HTMLResponse

    from pipecat.pipeline.pipeline import Pipeline

    from pipecat.pipeline.runner import PipelineRunner

    from pipecat.pipeline.task import PipelineTask, PipelineParams

    from pipecat.services.openai.llm import OpenAILLMService

    from pipecat.services.deepgram.stt import DeepgramSTTService

    from pipecat.services.cartesia.tts import CartesiaTTSService

    from pipecat.transports.network.fastapiwebsocket import (

    FastAPIWebsocketTransport,

    FastAPIWebsocketParams,

    )

    loaddotenv()

    @asynccontextmanager

    async def lifespan(app: FastAPI):

    print("Voice AI server starting...")

    yield

    print("Voice AI server shutting down...")

    app = FastAPI(lifespan=lifespan)

    @app.get("/")

    async def index():

    return HTMLResponse(content=open("static/index.html").read())

    @app.websocket("/ws")

    async def websocketendpoint(websocket: WebSocket):

    await websocket.accept()

    transport = FastAPIWebsocketTransport(

    websocket=websocket,

    params=FastAPIWebsocketParams(

    audioinenabled=True,

    audiooutenabled=True,

    addwavheader=False,

    vadenabled=True,

    vadaudiopassthrough=True,

    ),

    )

    stt = DeepgramSTTService(apikey=os.getenv("DEEPGRAMAPIKEY"))

    llm = OpenAILLMService(

    apikey=os.getenv("OPENAIAPIKEY"),

    model="gpt-4o-mini",

    systemprompt="You are a helpful voice assistant.",

    )

    tts = CartesiaTTSService(

    apikey=os.getenv("CARTESIAAPIKEY"),

    voiceid="a0e99841-438c-4a64-b679-ae501e7d6091",

    )

    pipeline = Pipeline([

    transport.input(),

    stt,

    llm,

    tts,

    transport.output(),

    ])

    task = PipelineTask(

    pipeline,

    params=PipelineParams(allowinterruptions=True),

    )

    runner = PipelineRunner()

    @transport.eventhandler("onclientconnected")

    async def onconnected(transport, client):

    print(f"Client connected: {client}")

    @transport.eventhandler("onclientdisconnected")

    async def ondisconnected(transport, client):

    print(f"Client disconnected: {client}")

    from pipecat.frames.frames import EndFrame

    await task.queueframes([EndFrame()])

    await runner.run(task)

    if name == "main":

    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

    Best Practices

    1. Latency Optimization

    Latency is a critical factor in voice AI. Here are tips to minimize it:

    # Use speed-optimized models
    

    llm = OpenAILLMService(

    apikey=os.getenv("OPENAIAPIKEY"),

    model="gpt-4o-mini", # Faster than gpt-4o

    temperature=0.7,

    maxtokens=150, # Limit response length

    )

    Use Cartesia for low-latency TTS

    tts = CartesiaTTSService(

    apikey=os.getenv("CARTESIAAPIKEY"),

    voiceid="your-voice-id",

    model="sonic-english", # Fastest model

    samplerate=24000,

    )

    Enable streaming across all layers

    params = PipelineParams(

    allowinterruptions=True,

    enablemetrics=True,

    )

    2. Robust Error Handling

    from pipecat.processors.frameprocessor import FrameProcessor
    

    from pipecat.frames.frames import Frame, ErrorFrame, TextFrame

    class ErrorHandler(FrameProcessor):

    """Handles pipeline errors gracefully."""

    def init(self, fallbackmessage: str = "Sorry, an error occurred. Please try again."):

    super().init()

    self.fallbackmessage = fallbackmessage

    self.errorcount = 0

    self.maxerrors = 5

    async def processframe(self, frame: Frame, direction):

    await super().processframe(frame, direction)

    if isinstance(frame, ErrorFrame):

    self.errorcount += 1

    print(f"[ERROR {self.errorcount}] {frame.error}")

    if self.errorcount >= self.maxerrors:

    print("[FATAL] Too many errors, shutting down pipeline")

    from pipecat.frames.frames import EndFrame

    await self.pushframe(EndFrame(), direction)

    return

    await self.pushframe(TextFrame(self.fallbackmessage), direction)

    return

    await self.pushframe(frame, direction)

    3. Conversation State Management

    from enum import Enum
    

    from pipecat.processors.frameprocessor import FrameProcessor

    from pipecat.frames.frames import Frame, TranscriptionFrame, TextFrame

    class ConversationState(Enum):

    GREETING = "greeting"

    LISTENING = "listening"

    PROCESSING = "processing"

    CONFIRMING = "confirming"

    FAREWELL = "farewell"

    class StatefulConversation(FrameProcessor):

    """Manages conversation state for a more structured flow."""

    def init(self):

    super().init()

    self.state = ConversationState.GREETING

    self.collecteddata = {}

    async def processframe(self, frame: Frame, direction):

    await super().processframe(frame, direction)

    if isinstance(frame, TranscriptionFrame):

    text = frame.text.lower()

    if self.state == ConversationState.GREETING:

    if any(word in text for word in ["hello", "hi", "hey"]):

    self.state = ConversationState.LISTENING

    await self.pushframe(

    Related Articles

    LiveKit Agents Tutorial: Building Real-Time AI Voice Agents with Python

    Tutorial LiveKit Agents: Membangun AI Voice Agent Real-Time dengan Python Pengantar LiveKit Agents adalah framework open...

    Prophet Tutorial: Time Series Forecasting with Python

    Tutorial Prophet: Time Series Forecasting dengan Python Time series forecasting adalah salah satu kebutuhan paling umum ...

    Complete MarkItDown Tutorial: Convert Documents to Markdown for AI Pipelines

    Tutorial Lengkap MarkItDown: Konversi Dokumen ke Markdown untuk Pipeline AI MarkItDown adalah library open-source dari M...

    Flower (flwr): A Complete Guide to Federated Learning in Python

    Tutorial Lengkap Flower (flwr): Framework Federated Learning dengan Python Federated learning adalah paradigma machine l...