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 agent secara real-time. Dikembangkan oleh tim Daily.co, Pipecat menyederhanakan proses kompleks dalam membangun conversational AI dengan menghubungkan berbagai layanan Speech-to-Text (STT), Large Language Model (LLM), dan Text-to-Speech (TTS) dalam sebuah pipeline yang efisien.
Dalam dunia AI yang semakin berkembang, voice AI agent menjadi salah satu aplikasi yang paling diminati. Mulai dari customer service otomatis, asisten virtual, hingga aplikasi kesehatan yang membutuhkan interaksi suara — semua membutuhkan infrastruktur yang handal untuk memproses audio secara real-time. Pipecat hadir untuk menjawab kebutuhan tersebut dengan arsitektur pipeline yang modular dan mudah dikustomisasi.
Tutorial ini akan memandu Anda dari instalasi dasar hingga pembuatan voice AI agent yang lengkap, termasuk integrasi dengan berbagai provider STT, LLM, dan TTS, serta deployment ke production.
Mengapa Pipecat?
Sebelum masuk ke implementasi, mari pahami mengapa Pipecat menjadi pilihan yang tepat untuk membangun voice AI agent:
Instalasi
Persyaratan Sistem
- Python 3.10 atau lebih baru
- pip atau uv sebagai package manager
- FFmpeg (untuk processing audio)
- PortAudio (untuk local audio I/O)
Instalasi Dasar
# Instalasi Pipecat core
pip install pipecat-ai
Instalasi dengan semua dependencies
pip install "pipecat-ai[all]"
Instalasi per Provider
Pipecat menggunakan sistem extras untuk menginstal dependencies sesuai provider yang Anda butuhkan:
# 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
Instalasi Kombinasi
Untuk skenario umum, Anda bisa menginstal beberapa extras sekaligus:
# Setup umum: Deepgram STT + OpenAI LLM + ElevenLabs TTS + Daily transport
pip install "pipecat-ai[deepgram,openai,elevenlabs,daily]"
Setup lokal untuk development
pip install "pipecat-ai[whisper,openai,cartesia,local]"
Instalasi FFmpeg dan PortAudio
# Ubuntu/Debian
sudo apt-get install ffmpeg portaudio19-dev
macOS
brew install ffmpeg portaudio
Windows (menggunakan Chocolatey)
choco install ffmpeg
Verifikasi Instalasi
import pipecat
print(f"Pipecat version: {pipecat.version}")
Cek ketersediaan modul
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.runner import PipelineRunner
from pipecat.pipeline.task import PipelineTask
print("Core modules loaded successfully!")
Konsep Dasar
Arsitektur Frame
Pipecat menggunakan konsep Frame sebagai unit data fundamental yang mengalir dalam pipeline. Setiap frame membawa tipe data tertentu:
from pipecat.frames.frames import (
AudioRawFrame, # Data audio mentah
TextFrame, # Teks biasa
TranscriptionFrame, # Hasil transkripsi STT
LLMMessagesFrame, # Pesan untuk LLM
TTSAudioRawFrame, # Audio hasil TTS
EndFrame, # Sinyal akhir pipeline
UserStartedSpeakingFrame, # User mulai berbicara
UserStoppedSpeakingFrame, # User berhenti berbicara
)
Pipeline dan Processor
Pipeline adalah rangkaian processor yang memproses frame secara berurutan:
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.runner import PipelineRunner
from pipecat.pipeline.task import PipelineTask, PipelineParams
Membuat pipeline sederhana
pipeline = Pipeline([
transport.input(), # Menerima audio dari user
sttservice, # Konversi speech ke text
llmservice, # Proses text dengan LLM
ttsservice, # Konversi response ke speech
transport.output(), # Kirim audio ke user
])
FrameProcessor Custom
Anda bisa membuat processor sendiri untuk menangani logic khusus:
from pipecat.processors.frameprocessor import FrameProcessor
from pipecat.frames.frames import Frame, TextFrame
class TextLoggerProcessor(FrameProcessor):
"""Processor yang mencatat semua TextFrame yang lewat."""
async def processframe(self, frame: Frame, direction):
await super().processframe(frame, direction)
if isinstance(frame, TextFrame):
print(f"[LOG] Text: {frame.text}")
# Teruskan frame ke processor berikutnya
await self.pushframe(frame, direction)
Basic Usage: Voice Bot Sederhana
Mari buat voice bot pertama Anda yang bisa menjawab pertanyaan secara 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 dengan 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():
# Konfigurasi transport lokal (mikrofon dan speaker)
transport = LocalAudioTransport(
micenabled=True,
speakerenabled=True,
micsamplerate=16000,
speakersamplerate=24000,
)
# Konfigurasi Speech-to-Text (Deepgram)
stt = DeepgramSTTService(
apikey=os.getenv("DEEPGRAMAPIKEY"),
language="id", # Bahasa Indonesia
)
# Konfigurasi LLM (OpenAI)
llm = OpenAILLMService(
apikey=os.getenv("OPENAIAPIKEY"),
model="gpt-4o",
systemprompt="""Kamu adalah asisten AI yang ramah dan membantu.
Jawab dalam bahasa Indonesia dengan singkat dan jelas.
Maksimal 2-3 kalimat per jawaban.""",
)
# Konfigurasi Text-to-Speech (ElevenLabs)
tts = ElevenLabsTTSService(
apikey=os.getenv("ELEVENLABSAPIKEY"),
voiceid="21m00Tcm4TlvDq8ikWAM", # Rachel voice
model="elevenmultilingualv2",
)
# Bangun pipeline
pipeline = Pipeline([
transport.input(),
stt,
llm,
tts,
transport.output(),
])
# Jalankan pipeline
task = PipelineTask(
pipeline,
params=PipelineParams(
allowinterruptions=True,
enablemetrics=True,
),
)
runner = PipelineRunner()
await runner.run(task)
if name == "main":
asyncio.run(main())
Voice Bot dengan Daily WebRTC
Untuk deployment berbasis web, gunakan Daily sebagai transport:
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():
# Konfigurasi 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']}")
# Sapa user saat bergabung
await task.queueframes([
TextFrame("Halo! Saya asisten AI Anda. Ada yang bisa saya bantu?")
])
@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 dengan Voice Bot
Integrasikan function calling untuk memberi kemampuan aksi kepada voice bot Anda:
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()
Definisikan tools/functions
tools = [
{
"type": "function",
"function": {
"name": "getweather",
"description": "Mendapatkan informasi cuaca untuk kota tertentu",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "Nama kota, contoh: Jakarta, Surabaya"
}
},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "gettime",
"description": "Mendapatkan waktu saat ini",
"parameters": {
"type": "object",
"properties": {}
}
}
},
{
"type": "function",
"function": {
"name": "setreminder",
"description": "Mengatur pengingat untuk user",
"parameters": {
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "Pesan pengingat"
},
"minutes": {
"type": "integer",
"description": "Berapa menit dari sekarang"
}
},
"required": ["message", "minutes"]
}
}
}
]
Implementasi function handlers
async def handlegetweather(city: str) -> str:
# Dalam produksi, panggil API cuaca yang sesungguhnya
weatherdata = {
"Jakarta": {"temp": 32, "condition": "Berawan", "humidity": 75},
"Surabaya": {"temp": 34, "condition": "Cerah", "humidity": 65},
"Bandung": {"temp": 24, "condition": "Hujan ringan", "humidity": 85},
}
data = weatherdata.get(city, {"temp": 28, "condition": "Tidak diketahui", "humidity": 70})
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("%d %B %Y")
})
async def handlesetreminder(message: str, minutes: int) -> str:
return json.dumps({
"status": "success",
"message": f"Pengingat '{message}' diatur untuk {minutes} menit dari sekarang"
})
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"),
language="id",
)
llm = OpenAILLMService(
apikey=os.getenv("OPENAIAPIKEY"),
model="gpt-4o",
systemprompt="""Kamu adalah asisten AI yang bisa membantu dengan cuaca,
waktu, dan pengingat. Gunakan function calling jika diperlukan.
Jawab dalam bahasa Indonesia.""",
tools=tools,
)
# Register function handler
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 dan Memory
Kelola konteks percakapan untuk pengalaman yang lebih natural:
from pipecat.processors.frameprocessor import FrameProcessor
from pipecat.frames.frames import Frame, TranscriptionFrame, TextFrame
class ConversationMemory(FrameProcessor):
"""Menyimpan riwayat percakapan dan menyediakan konteks."""
def init(self, max
turns: 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
Integrasikan kemampuan vision untuk memproses gambar bersamaan dengan suara:
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):
"""Memproses frame gambar dan mengirim ke LLM untuk analisis."""
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
# Encode gambar ke base64
imageb64 = base64.b64encode(frame.image).decode("utf-8")
# Kirim ke LLM dengan vision capability
messages = [
{
"role": "user",
"content": [
{
"type": "imageurl",
"imageurl": {
"url": f"data:image/jpeg;base64,{imageb64}"
}
},
{
"type": "text",
"text": "Deskripsikan apa yang kamu lihat dalam gambar ini."
}
]
}
]
# Process vision request
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, # Aktifkan kamera input
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. Interrupt Handling yang Baik
Menangani interupsi dari user saat bot sedang berbicara:
from pipecat.pipeline.task import PipelineParams
Konfigurasi interrupt handling
params = PipelineParams(
allowinterruptions=True,
enablemetrics=True,
reportonlyinitialttfb=True,
)
Custom interrupt handler
class SmartInterruptHandler(FrameProcessor):
"""Handler yang mendeteksi dan merespons interupsi user secara cerdas."""
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 dan Monitoring
Pantau performa pipeline Anda:
from pipecat.processors.frameprocessor import FrameProcessor
from pipecat.frames.frames import Frame, MetricsFrame
import time
class MetricsCollector(FrameProcessor):
"""Mengumpulkan metrik performa pipeline."""
def init(self):
super().init()
self.metrics = {
"total
frames": 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 untuk Integrasi Web
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():
# WebSocket server transport
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 untuk terhubung:
// web-client.js
const socket = new WebSocket("ws://localhost:8765");
// Setup audio context
const audioContext = new AudioContext({ sampleRate: 24000 });
const mediaRecorder = null;
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 dengan FastAPI
Untuk production, integrasikan Pipecat dengan FastAPI:
import asyncio
import os
from contextlib import asynccontextmanager
from dotenv import loaddotenv
from fastapi import FastAPI, WebSocket, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
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}")
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. Optimasi Latensi
Latensi adalah faktor kunci dalam voice AI. Berikut tips untuk meminimalkannya:
# Gunakan model yang dioptimalkan untuk kecepatan
llm = OpenAILLMService(
apikey=os.getenv("OPENAIAPIKEY"),
model="gpt-4o-mini", # Lebih cepat dari gpt-4o
temperature=0.7,
maxtokens=150, # Batasi panjang respons
)
Gunakan Cartesia untuk TTS dengan latensi rendah
tts = CartesiaTTSService(
apikey=os.getenv("CARTESIAAPIKEY"),
voiceid="your-voice-id",
model="sonic-english", # Model tercepat
samplerate=24000,
)
Aktifkan streaming di semua layer
params = PipelineParams(
allowinterruptions=True,
enablemetrics=True,
)
2. Error Handling yang Robust
from pipecat.processors.frameprocessor import FrameProcessor
from pipecat.frames.frames import Frame, ErrorFrame
class ErrorHandler(FrameProcessor):
"""Menangani error dalam pipeline dengan graceful."""
def init(self, fallback
message: str = "Maaf, terjadi kesalahan. Silakan coba lagi."):
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
# Kirim pesan fallback ke user
await self.pushframe(TextFrame(self.fallbackmessage), direction)
return
await self.pushframe(frame, direction)
3. Manajemen State Percakapan
from enum import Enum
from pipecat.processors.frameprocessor import FrameProcessor