流程與工作流程
[VoicePipeline
][agents.voice.pipeline.VoicePipeline] 是一個讓你輕鬆將 agent 工作流程轉換為語音應用程式的類別。你只需傳入要執行的工作流程,語音處理流程(voice pipeline)就會自動處理輸入音訊的轉錄、偵測音訊結束的時機、在正確的時機呼叫你的工作流程,並將工作流程的輸出轉換回音訊。
graph LR
%% Input
A["🎤 Audio Input"]
%% Voice Pipeline
subgraph Voice_Pipeline [Voice Pipeline]
direction TB
B["Transcribe (speech-to-text)"]
C["Your Code"]:::highlight
D["Text-to-speech"]
B --> C --> D
end
%% Output
E["🎧 Audio Output"]
%% Flow
A --> Voice_Pipeline
Voice_Pipeline --> E
%% Custom styling
classDef highlight fill:#ffcc66,stroke:#333,stroke-width:1px,font-weight:700;
設定語音處理流程 (pipeline)
當你建立一個語音處理流程時,可以設定以下幾項內容:
- [
workflow
][agents.voice.workflow.VoiceWorkflowBase]:這是每次新音訊被轉錄時所執行的程式碼。 - [
speech-to-text
][agents.voice.model.STTModel] 與 [text-to-speech
][agents.voice.model.TTSModel]:所使用的語音辨識(STT)與文字轉語音(TTS)模型。 - [
config
][agents.voice.pipeline_config.VoicePipelineConfig]:可用來設定以下項目:- 模型提供者(model provider):可將模型名稱對應到實際模型
- 追蹤(tracing):包含是否停用追蹤、是否上傳音訊檔案、流程名稱、追蹤 ID 等
- TTS 與 STT 模型的相關設定,例如提示詞 (prompt)、語言與使用的資料型態等
執行語音處理流程
你可以透過 [run()
][agents.voice.pipeline.VoicePipeline.run] 方法來執行語音處理流程,該方法允許你以兩種形式傳入音訊輸入:
- [
AudioInput
][agents.voice.input.AudioInput]:當你已經擁有完整的音訊轉錄內容,只需針對該內容產生結果時使用。這在你不需要偵測說話者何時結束時特別有用,例如處理預錄音訊,或在「按住說話」的應用程式中,使用者何時說完很明確。 - [
StreamedAudioInput
][agents.voice.input.StreamedAudioInput]:當你需要偵測使用者何時說完時使用。它允許你隨時推送偵測到的音訊片段,語音處理流程會在適當時機自動執行 agent workflow,這個過程稱為「活動偵測(activity detection)」。
執行結果
語音處理流程執行的結果會是一個 [StreamedAudioResult
][agents.voice.result.StreamedAudioResult] 物件。這個物件允許你在事件發生時即時串流取得。常見的 [VoiceStreamEvent
][agents.voice.events.VoiceStreamEvent] 事件類型包括:
- [
VoiceStreamEventAudio
][agents.voice.events.VoiceStreamEventAudio]:包含一段音訊片段。 - [
VoiceStreamEventLifecycle
][agents.voice.events.VoiceStreamEventLifecycle]:通知你像是一次輪流(turn)開始或結束等生命週期事件。 - [
VoiceStreamEventError
][agents.voice.events.VoiceStreamEventError]:錯誤事件。
result = await pipeline.run(input)
async for event in result.stream():
if event.type == "voice_stream_event_audio":
# play audio
elif event.type == "voice_stream_event_lifecycle":
# lifecycle
elif event.type == "voice_stream_event_error"
# error
...
最佳實踐
中斷處理
Agents SDK 目前尚未針對 [StreamedAudioInput
][agents.voice.input.StreamedAudioInput] 提供任何內建的中斷(interruptions)支援。因此,每當偵測到一個輪流(turn)時,系統會為每個偵測到的輪流分別觸發一次你的工作流程。如果你希望在應用程式內處理中斷,可以監聽 [VoiceStreamEventLifecycle
][agents.voice.events.VoiceStreamEventLifecycle] 事件。turn_started
會表示新的輪流已經被轉錄並開始處理;turn_ended
則會在該輪流的所有音訊傳送完畢後觸發。你可以利用這些事件,在模型開始一個輪流時將說話者的麥克風靜音,並在你將該輪流的所有相關音訊清空後再解除靜音。