关于 voice-ai
voice-ai 是面向开发者的技能,用于构建生产级语音 AI Agent。它介绍由 Deepgram、Groq、Cartesia 和 Twilio 组成的流式方案,并涵盖延迟优化、双语提示词和打断处理。
主要功能
- 01基于 VAD 的 Deepgram 流式语音识别
- 02面向语音优化的 Groq LLM 响应
- 03Cartesia 流式语音合成与情绪控制
- 04Twilio Media Streams WebSocket 处理
- 05英语和西班牙语支持
适用场景
- 01构建实时电话语音 Agent
- 02为语音管线添加语音识别
- 03生成富有表现力的语音回复
- 04排查语音技术栈的延迟瓶颈
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ scientiacapital/ skills --skill voice-ai安装后在 Claude Code 中输入/voice-ai确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
config.jsonreference/cartesia-tts.mddeepgram-setup.mdgroq-voice-llm.mdlatency-optimization.mdtwilio-webhooks.mdvoice-prompts.mdtemplates/voice-agent-starter.py详细介绍
- STT - Deepgram Nova-3 流式转录(约 150ms)
- LLM - Groq llama-3.1-8b-instant,实现最快推理(约 220ms)
- TTS - Cartesia Sonic,打造超逼真的语音(约 90ms)
- 电话系统 - Twilio Media Streams,实现实时双向音频
重要:禁止使用 OPENAI - 绝不要使用 from openai import OpenAI
主要交付内容:
- 带语音活动检测的流式 STT
- 针对语音优化的低延迟 LLM 响应
- 支持情绪控制、富有表现力的 TTS
- Twilio Media Streams WebSocket 处理程序
<quick_start> 最精简的语音管线(约 50 行,低于 500ms):
import os
import asyncio
from groq import AsyncGroq
from deepgram import AsyncDeepgramClient
from cartesia import AsyncCartesia
# NEVER: from openai import OpenAI
async def voice_pipeline(user_audio: bytes) -> bytes:
"""Process audio input, return audio response."""
# 1. STT: Deepgram Nova-3 (~150ms)
dg = AsyncDeepgramClient(api_key=os.getenv("DEEPGRAM_API_KEY"))
result = await dg.listen.rest.v1.transcribe(
{"buffer": user_audio, "mimetype": "audio/wav"},
{"model": "nova-3", "language": "en-US"}
)
user_text = result.results.channels[0].alternatives[0].transcript
# 2. LLM: Groq (~220ms) - NOT OpenAI
groq = AsyncGroq(api_key=os.getenv("GROQ_API_KEY"))
response = await groq.chat.completions.create(
model="llama-3.1-8b-instant",
messages=[
{"role": "system", "content": "Keep responses under 2 sentences."},
{"role": "user", "content": user_text}
],
max_tokens=150
)
response_text = response.choices[0].message.content
# 3. TTS: Cartesia Sonic-2 (~90ms)
cartesia = AsyncCartesia(api_key=os.getenv("CARTESIA_API_KEY"))
audio_chunks = []
for chunk in cartesia.tts.sse(
model_id="sonic-2",
transcript=response_text,
voice={"id": "f9836c6e-a0bd-460e-9d3c-f7299fa60f94"},
output_format={"container": "raw", "encoding": "pcm_s16le", "sample_rate": 8000}
):
if chunk.audio:
audio_chunks.append(chunk.audio)
return b"".join(audio_chunks) # Total: ~460ms
</quick_start>
<success_criteria> 语音 AI Agent 满足以下条件即视为成功:
- 总延迟低于 500ms(STT + LLM + TTS)
- STT 能正确转录并检测话语结束
- TTS 听起来自然且符合对话语境
- 可流畅处理插话(打断)(Enterprise 版本)
- 双语支持可处理语言切换 </success_criteria>
<optimal_stack>
VozLux 测试过的技术栈
| 组件 | 提供商 | 模型 | 延迟 | 备注 |
|---|---|---|---|---|
| STT | Deepgram | Nova-3 | 约 150ms | 流式、VAD、话语检测 |
| LLM | Groq | llama-3.1-8b-instant | 约 220ms | LPU 硬件,最快推理 |
| TTS | Cartesia | Sonic-2 | 约 90ms | 流式、情绪、双语 |
| 总计 | - | - | 约 460ms | 达成低于 500ms 的目标 |
LLM 优先级(绝不使用 OpenAI)
LLM_PRIORITY = [
("groq", "GROQ_API_KEY", "~220ms"), # Primary
("cerebras", "CEREBRAS_API_KEY", "~200ms"), # Fallback
("anthropic", "ANTHROPIC_API_KEY", "~500ms"), # Quality fallback
]
# NEVER: from openai import OpenAI
分层架构
| 层级 | 延迟 | STT | LLM | TTS | 功能 |
|---|---|---|---|---|---|
| 免费 | 3000ms | TwiML Gather | Groq | Polly | 基础 IVR |
| 专业版 | 600ms | Deepgram Nova | Groq | Cartesia | Media Streams |
| 企业版 | 400ms | Deepgram + VAD | Groq | Cartesia | 插话处理 |
| </optimal_stack> |
<deepgram_stt>
Deepgram STT(v5 SDK)
流式 WebSocket 模式
from deepgram import AsyncDeepgramClient
from deepgram.core.events import EventType
from deepgram.extensions.types.sockets import (
ListenV1SocketClientResponse,
ListenV1MediaMessage,
ListenV1ControlMessage
)
async def streaming_stt():
client = AsyncDeepgramClient(api_key=os.getenv("DEEPGRAM_API_KEY"))
async with client.listen.v1.connect(model="nova-3") as connection:
def on_message(message: ListenV1SocketClientResponse):
msg_type = getattr(message, "type", None)
if msg_type == "Results":
channel = getattr(message, "channel", None)
if channel and channel.alternatives:
text = channel.alternatives[0].transcript
is_final = getattr(message, "is_final", False)
if text:
print(f"{'[FINAL]' if is_final else '[INTERIM]'} {text}")
elif msg_type == "UtteranceEnd":
print("[USER FINISHED SPEAKING]")
elif msg_type == "SpeechStarted":
print("[USER STARTED SPEAKING - barge-in trigger]")
connection.on(EventType.MESSAGE, on_message)
await connection.start_listening()
# Send audio chunks
await connection.send_media(ListenV1MediaMessage(data=audio_bytes))
# Keep alive for long sessions
await connection.send_control(ListenV1ControlMessage(type="KeepAlive"))
连接选项
options = {
"model": "nova-3",
"language": "en-US",
"encoding": "mulaw", # Twilio format
"sample_rate": 8000, # Telephony standard
"interim_results": True, # Get partial transcripts
"utterance_end_ms": 1000, # Silence to end utterance
"vad_events": True, # Voice activity detection
}
完整的流式配置请参阅
reference/deepgram-setup.md。 </deepgram_stt>
<groq_llm>
Groq LLM(最快推理)
语音优化模式
from groq import AsyncGroq
class GroqVoiceLLM:
def __init__(self, model: str = "llama-3.1-8b-instant"):
self.client = AsyncGroq()
self.model = model
self.system_prompt = (
"You are a helpful voice assistant. "
"Keep responses to 2-3 sentences max. "
"Speak naturally as if on a phone call."
)
async def generate_stream(self, user_input: str):
"""Streaming for lowest TTFB."""
stream = await self.client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": self.system_prompt},
{"role": "user", "content": user_input}
],
max_tokens=150,
temperature=0.7,
stream=True,
)
async for chunk in stream:
content = chunk.choices[0].delta.content
if content:
yield content # Pipe to TTS immediately
模型选择
| 模型 | 速度 | 质量 | 使用场景 |
|---|---|---|---|
| llama-3.1-8b-instant | 约 220ms | 良好 | 主要语音模型 |
| llama-3.3-70b-versatile | 约 500ms | 最佳 | 复杂查询 |
| mixtral-8x7b-32768 | 约 300ms | 良好 | 长上下文 |
上下文管理请参阅
reference/groq-voice-llm.md。 </groq_llm>
<cartesia_tts>
Cartesia TTS(Sonic-2)
流式模式
from cartesia import AsyncCartesia
class CartesiaTTS:
VOICES = {
"en": "f9836c6e-a0bd-460e-9d3c-f7299fa60f94", # Warm female
"es": "5c5ad5e7-1020-476b-8b91-fdcbe9cc313c", # Mexican Spanish
}
EMOTIONS = {
"greeting": "excited",
"confirmation": "grateful",
"info": "calm",
"complaint": "sympathetic",
"apology": "apologetic",
}
def __init__(self, api_key: str):
self.client = AsyncCartesia(api_key=api_key)
async def synthesize_stream(
self,
text: str,
language: str = "en",
emotion: str = "neutral"
):
voice_id = self.VOICES.get(language, self.VOICES["en"])
response = self.client.tts.sse(
model_id="sonic-2",
transcript=text,
voice={
"id": voice_id,
"experimental_controls": {
"speed": "normal",
"emotion": [emotion] if emotion != "neutral" else []
}
},
language=language,
output_format={
"container": "raw",
"encoding": "pcm_s16le",
"sample_rate": 8000, # Telephony
},
)
for chunk in response:
if chunk.audio:
yield chunk.audio
携带时间戳
response = client.tts.sse(
model_id="sonic-2",
transcript="Hello, world!",
voice={"id": voice_id},
output_format={"container": "raw", "encoding": "pcm_f32le", "sample_rate": 44100},
add_timestamps=True,
)
for chunk in response:
if chunk.word_timestamps:
for word, start, end in zip(
chunk.word_timestamps.words,
chunk.word_timestamps.start,
chunk.word_timestamps.end
):
print(f"'{word}': {start:.2f}s - {end:.2f}s")
全部 57 种情绪请参阅
reference/cartesia-tts.md。 </cartesia_tts>
<twilio_media_streams>
Twilio Media Streams
WebSocket 处理程序(FastAPI)
from fastapi import FastAPI, WebSocket, Request
from fastapi.responses import Response
from twilio.twiml.voice_response import VoiceResponse, Connect, Stream
import json, base64, audioop
app = FastAPI()
@app.post("/voice/incoming")
async def incoming_call(request: Request):
"""Route to Media Streams WebSocket."""
form = await request.form()
caller = form.get("From", "")
lang = "es" if caller.startswith("+52") else "en"
response = VoiceResponse()
connect = Connect()
connect.append(Stream(url=f"wss://your-app.com/voice/stream?lang={lang}"))
response.append(connect)
return Response(content=str(response), media_type="application/xml")
@app.websocket("/voice/stream")
async def media_stream(websocket: WebSocket, lang: str = "en"):
await websocket.accept()
stream_sid = None
while True:
message = await websocket.receive_text()
data = json.loads(message)
if data["event"] == "start":
stream_sid = data["start"]["streamSid"]
# Initialize STT, send greeting
elif data["event"] == "media":
audio = base64.b64decode(data["media"]["payload"])
# Send to Deepgram STT
elif data["event"] == "stop":
break
async def send_audio(websocket, stream_sid: str, pcm_audio: bytes):
"""Convert PCM to mu-law and send to Twilio."""
mulaw = audioop.lin2ulaw(pcm_audio, 2)
await websocket.send_text(json.dumps({
"event": "media",
"streamSid": stream_sid,
"media": {"payload": base64.b64encode(mulaw).decode()}
}))
完整的处理程序请参阅
reference/twilio-webhooks.md。 </twilio_media_streams>
<bilingual_support>
双语支持(EN/ES)
自动检测
def detect_language(caller_number: str) -> str:
if caller_number.startswith("+52"):
return "es" # Mexico
elif caller_number.startswith("+1"):
return "en" # US/Canada
return "es" # Default Spanish
语音提示词
GREETINGS = {
"en": "Hello! How can I help you today?",
"es": "Hola! En que puedo ayudarle hoy?", # Use "usted" for respect
}
</bilingual_support>
<voice_prompts>
语音提示词工程
VOICE_PROMPT = """
# Role
You are a bilingual voice assistant for {business_name}.
# Tone
- 2-3 sentences max for phone clarity
- NEVER use bullet points, lists, or markdown
- Spell out emails: "john at company dot com"
- Phone numbers with pauses: "five one two... eight seven seven..."
- Spanish: Use "usted" for formal respect
# Guardrails
- Never make up information
- Transfer to human after 3 failed attempts
- Match caller's language
# Error Recovery
English: "I want to make sure I got that right. Did you say [repeat]?"
Spanish: "Quiero asegurarme de entender bien. Dijo [repetir]?"
"""
完整模板请参阅
reference/voice-prompts.md。 </voice_prompts>
<file_locations>
参考文件
reference/deepgram-setup.md- 完整的流式 STT 配置reference/groq-voice-llm.md- Groq 语音模式reference/cartesia-tts.md- 全部 57 种情绪、语音克隆reference/twilio-webhooks.md- 完整的 Media Streams 处理程序reference/latency-optimization.md- 低于 500ms 的优化技术reference/voice-prompts.md- 语音优化提示词 </file_locations>
用户需要语音 Agent: → 提供完整技术栈(Deepgram + Groq + Cartesia + Twilio) → 从 quick_start 流水线开始
用户只需要 STT:
→ 提供 Deepgram 流式处理模式
→ 参考:reference/deepgram-setup.md
用户只需要 TTS:
→ 提供带情感表达的 Cartesia 模式
→ 参考:reference/cartesia-tts.md
用户需要优化延迟:
→ 审查当前技术栈,找出瓶颈
→ 参考:reference/latency-optimization.md
用户提到 OpenAI: → 立即将其转向 Groq → 说明:“不使用 OPENAI——使用 Groq 以实现最低延迟”
<env_setup>
环境变量
# Required (NEVER OpenAI)
DEEPGRAM_API_KEY=your_key
GROQ_API_KEY=gsk_xxxx
CARTESIA_API_KEY=your_key
# Twilio
TWILIO_ACCOUNT_SID=ACxxxx
TWILIO_AUTH_TOKEN=your_token
TWILIO_PHONE_NUMBER=+15551234567
# Fallbacks
ANTHROPIC_API_KEY=sk-ant-xxxx
CEREBRAS_API_KEY=csk_xxxx
pip install deepgram-sdk groq cartesia twilio fastapi
</env_setup>
<quick_reference>
快速参考卡
STACK:
STT: Deepgram Nova-3 (~150ms)
LLM: Groq llama-3.1-8b-instant (~220ms) - NOT OPENAI
TTS: Cartesia Sonic-2 (~90ms)
LATENCY TARGETS:
Pro: 600ms (Media Streams)
Enterprise: 400ms (Full streaming + barge-in)
BILINGUAL:
+52 -> Spanish (es)
+1 -> English (en)
Default -> Spanish
EMOTIONS (Cartesia):
greeting -> excited
confirmation -> grateful
complaint -> sympathetic
写入结果旁文件
写入 ~/.claude/skill-analytics/last-outcome-voice-ai.json:
{"ts":"[UTC ISO8601]","skill":"voice-ai","version":"1.0.0","variant":"default","status":"[success|partial|error]","runtime_ms":[ms],"metrics":{"agents_built":[n],"endpoints_configured":[n],"latency_targets_met":[n]},"error":null,"session_id":"[YYYY-MM-DD]"}
</quick_reference>