mcpField
V
voice-ai-development

voice-ai-development

github.com/davila7开发33.0k347 次安装今天更新
代码仓库

关于 voice-ai-development

面向实时语音应用开发者的技能,适用于构建语音 Agent 和音频流程。内容涵盖服务提供方选择、流式处理、延迟优化与打断处理。

主要功能

  1. 01OpenAI Realtime API 实践模式
  2. 02Vapi 语音 Agent 开发
  3. 03Deepgram 语音识别与 ElevenLabs 合成
  4. 04WebRTC 音频处理
  5. 05流式处理与延迟优化
  6. 06插话与打断处理

适用场景

  1. 01构建电话语音 Agent
  2. 02创建实时语音到语音应用
  3. 03组合定制转录与语音合成流程

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/davila7/claude-code-templates --skill voice-ai-development

安装后在 Claude Code 中输入/voice-ai-development确认已加载。

详细介绍

语音 AI 开发

角色:语音 AI 架构师

你擅长构建实时语音应用。你会从延迟预算、音频质量和用户体验的角度思考。你知道,语音应用响应迅速时会显得神奇,响应缓慢时则会让人觉得出了问题。你会根据每种用例选择合适的服务提供商组合,并持续优化感知响应速度。

能力

  • OpenAI Realtime API
  • Vapi 语音 Agent
  • Deepgram STT/TTS
  • ElevenLabs 语音合成
  • LiveKit 实时基础设施
  • WebRTC 音频处理
  • 语音 Agent 设计
  • 延迟优化

要求

  • Python 或 Node.js
  • 服务提供商的 API 密钥
  • 音频处理知识

模式

OpenAI Realtime API

使用 GPT-4o 实现原生语音到语音

适用场景:希望获得集成式语音 AI,无需单独使用 STT/TTS 时

import asyncio
import websockets
import json
import base64

OPENAI_API_KEY = "sk-..."

async def voice_session():
    url = "wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview"
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "OpenAI-Beta": "realtime=v1"
    }

    async with websockets.connect(url, extra_headers=headers) as ws:
        # Configure session
        await ws.send(json.dumps({
            "type": "session.update",
            "session": {
                "modalities": ["text", "audio"],
                "voice": "alloy",  # alloy, echo, fable, onyx, nova, shimmer
                "input_audio_format": "pcm16",
                "output_audio_format": "pcm16",
                "input_audio_transcription": {
                    "model": "whisper-1"
                },
                "turn_detection": {
                    "type": "server_vad",  # Voice activity detection
                    "threshold": 0.5,
                    "prefix_padding_ms": 300,
                    "silence_duration_ms": 500
                },
                "tools": [
                    {
                        "type": "function",
                        "name": "get_weather",
                        "description": "Get weather for a location",
                        "parameters": {
                            "type": "object",
                            "properties": {
                                "location": {"type": "string"}
                            }
                        }
                    }
                ]
            }
        }))

        # Send audio (PCM16, 24kHz, mono)
        async def send_audio(audio_bytes):
            await ws.send(json.dumps({
                "type": "input_audio_buffer.append",
                "audio": base64.b64encode(audio_bytes).decode()
            }))

        # Receive events
        async for message in ws:
            event = json.loads(message)

            if event["type"] == "resp
Vapi 语音 Agent

使用 Vapi 平台构建语音 Agent

适用场景:基于电话的 Agent、快速部署

# Vapi provides hosted voice agents with webhooks

from flask import Flask, request, jsonify
import vapi

app = Flask(__name__)
client = vapi.Vapi(api_key="...")

# Create an assistant
assistant = client.assistants.create(
    name="Support Agent",
    model={
        "provider": "openai",
        "model": "gpt-4o",
        "messages": [
            {
                "role": "system",
                "content": "You are a helpful support agent..."
            }
        ]
    },
    voice={
        "provider": "11labs",
        "voiceId": "21m00Tcm4TlvDq8ikWAM"  # Rachel
    },
    firstMessage="Hi! How can I help you today?",
    transcriber={
        "provider": "deepgram",
        "model": "nova-2"
    }
)

# Webhook for conversation events
@app.route("/vapi/webhook", methods=["POST"])
def vapi_webhook():
    event = request.json

    if event["type"] == "function-call":
        # Handle tool call
        name = event["functionCall"]["name"]
        args = event["functionCall"]["parameters"]

        if name == "check_order":
            result = check_order(args["order_id"])
            return jsonify({"result": result})

    elif event["type"] == "end-of-call-report":
        # Call ended - save transcript
        transcript = event["transcript"]
        save_transcript(event["call"]["id"], transcript)

    return jsonify({"ok": True})

# Start outbound call
call = client.calls.create(
    assistant_id=assistant.id,
    customer={
        "number": "+1234567890"
    },
    phoneNumber={
        "twilioPhoneNumber": "+0987654321"
    }
)

# Or create web call
web_call = client.calls.create(
    assistant_id=assistant.id,
    type="web"
)
# Returns URL for WebRTC connection
Deepgram STT + ElevenLabs TTS

一流的转录与语音合成

适用场景:追求高质量语音、自定义管线时

import asyncio
from deepgram import DeepgramClient, LiveTranscriptionEvents
from elevenlabs import ElevenLabs

# Deepgram real-time transcription
deepgram = DeepgramClient(api_key="...")

async def transcribe_stream(audio_stream):
    connection = deepgram.listen.live.v("1")

    async def on_transcript(result):
        transcript = result.channel.alternatives[0].transcript
        if transcript:
            print(f"Heard: {transcript}")
            if result.is_final:
                # Process final transcript
                await handle_user_input(transcript)

    connection.on(LiveTranscriptionEvents.Transcript, on_transcript)

    await connection.start({
        "model": "nova-2",  # Best quality
        "language": "en",
        "smart_format": True,
        "interim_results": True,  # Get partial results
        "utterance_end_ms": 1000,
        "vad_events": True,  # Voice activity detection
        "encoding": "linear16",
        "sample_rate": 16000
    })

    # Stream audio
    async for chunk in audio_stream:
        await connection.send(chunk)

    await connection.finish()

# ElevenLabs streaming synthesis
eleven = ElevenLabs(api_key="...")

def text_to_speech_stream(text: str):
    """Stream TTS audio chunks."""
    audio_stream = eleven.text_to_speech.convert_as_stream(
        voice_id="21m00Tcm4TlvDq8ikWAM",  # Rachel
        model_id="eleven_turbo_v2_5",  # Fastest
        text=text,
        output_format="pcm_24000"  # Raw PCM for low latency
    )

    for chunk in audio_stream:
        yield chunk

# Or with WebSocket for lowest latency
async def tts_websocket(text_stream):
    async with eleven.text_to_speech.stream_async(
        voice_id="21m00Tcm4TlvDq8ikWAM",
        model_id="eleven_turbo_v2_5"
    ) as tts:
        async for text_chunk in text_stream:
            audio = await tts.send(text_chunk)
            yield audio

        # Flush remaining audio
        final_audio = await tts.flush()
        yield final_audio

反模式

❌ 非流式管线

问题所在:会增加数秒延迟。 用户会觉得响应缓慢。 对话流程会中断。

改进方式:所有环节都使用流式处理:

  • STT:中间结果
  • LLM:Token 流式传输
  • TTS:分块流式传输 在 LLM 完成前就启动 TTS。
❌ 忽略打断

问题所在:用户体验令人沮丧。 感觉像是在和机器说话。 浪费时间。

改进方式:实现插话检测。 使用 VAD 检测用户语音。 立即停止 TTS。 清空音频队列。

❌ 绑定单一服务提供商

问题所在:质量可能不是最优。 存在单点故障。 更难进行优化。

改进方式:组合使用各领域最佳服务提供商:

  • STT 使用 Deepgram(速度 + 准确度)
  • TTS 使用 ElevenLabs(语音质量)
  • LLM 使用 OpenAI/Anthropic

限制

  • 延迟因服务提供商而异
  • 每分钟费用会逐渐累积
  • 质量取决于网络
  • 调试复杂

相关技能

适合搭配:langgraph、structured-output、langfuse

评论

支持 Markdown