语音 Agent:三明治架构实现语音助手

Published by rcdfrd on 2026-02-17

语音 Agent:三明治架构实现语音助手

语音 Agent 有两种架构。端到端架构直接用多模态模型处理音频输入输出,门槛高。三明治架构是更实用的方案:语音转文字、Agent 处理、文字转语音。

语音转文字

用 OpenAI 的 Whisper 模型做 STT:

from openai import OpenAI

stt_client = OpenAI()

with open("data/hello.mp3", "rb") as audio_file:
    transcription = stt_client.audio.transcriptions.create(
        model="whisper-large-v3",
        file=audio_file,
        response_format="text",
    )
print(transcription)

Agent 处理

中间环节就是普通的 LangChain Agent,注意系统提示词要告诉模型「你的回答会被朗读」:

from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver

agent = create_agent(
    model="openai:gpt-4.1-mini",
    system_prompt="""你是一个语音助手。
    不要使用表情符号、特殊字符或 markdown。
    你的回答将由文本转语音引擎朗读。""",
    checkpointer=InMemorySaver(),
)

responses = []
for message, _ in agent.stream(
    {"messages": [HumanMessage(content=transcription)]},
    {"configurable": {"thread_id": "1"}},
    stream_mode="messages",
):
    if message.text:
        responses.append(message.text)

response_text = "".join(responses)

文字转语音

用微软的 edge-tts 做 TTS,免费且中文效果不错:

import edge_tts

communicate = edge_tts.Communicate(response_text, "zh-CN-XiaoxiaoNeural")
with open("output.mp3", "wb") as f:
    for chunk in communicate.stream_sync():
        if chunk["type"] == "audio":
            f.write(chunk["data"])

zh-CN-XiaoxiaoNeural 是晓晓的声音,自然度很高。edge-tts 还支持几十种其他语音。

小结

三明治架构简单粗暴但管用。每个环节都可以独立替换:STT 可以换成 faster-whisper,Agent 可以加工具,TTS 可以换成付费的更自然的引擎。三层解耦,灵活度很高。