Merge pull request #27 from Plaud-AI/feat/demo

feat: interruption report && system prompt && vad instance
This commit is contained in:
Harold-Guo 2025-12-08 18:00:05 +08:00 committed by GitHub
commit 2fcfbd32bc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 131 additions and 178 deletions

View file

@ -877,7 +877,7 @@ class ConnectionHandler:
False, False,
) )
init_vad = False init_vad = True
init_asr = True init_asr = True
try: try:
@ -1377,6 +1377,9 @@ class ConnectionHandler:
self.client_audio_buffer = bytearray() self.client_audio_buffer = bytearray()
self.client_have_voice = False self.client_have_voice = False
self.client_voice_stop = False self.client_voice_stop = False
# reset VAD exponential filter
# if self.vad:
# self.vad.reset_filter()
self.logger.bind(tag=TAG).debug("VAD states reset.") self.logger.bind(tag=TAG).debug("VAD states reset.")
def chat_and_close(self, text): def chat_and_close(self, text):

View file

@ -364,7 +364,11 @@ class TTSProviderBase(ABC):
continue continue
if self.conn.client_abort: if self.conn.client_abort:
logger.bind(tag=TAG).debug("收到打断信号,跳过当前音频数据") logger.bind(tag=TAG).debug("receive interruption, report the played content and skip the subsequent audio")
# report the played content when interruption occurs
if enqueue_text is not None and enqueue_audio is not None and len(enqueue_audio) > 0:
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio, message_tag)
logger.bind(tag=TAG).info(f"report the played content when interruption occurs: {enqueue_text[:50] if enqueue_text else ''}...")
enqueue_text, enqueue_audio = None, [] enqueue_text, enqueue_audio = None, []
last_send_future = None last_send_future = None
continue continue

View file

@ -165,17 +165,10 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).debug( logger.bind(tag=TAG).debug(
f"Received TTS task | {message.sentence_type.name} | {message.content_type.name}" f"Received TTS task | {message.sentence_type.name} | {message.content_type.name}"
) )
if message.sentence_type == SentenceType.FIRST: if message.sentence_type == SentenceType.FIRST:
# ========== New dialogue round starts ==========
self.conn.client_abort = False self.conn.client_abort = False
self.tts_audio_first_sentence = True
self._first_sent = False
self._session_text_buffer = []
self.conn._latency_tts_first_text_time = None # Reset TTS input time
self._message_tag = message.message_tag
elif self.conn.client_abort: if self.conn.client_abort:
# ========== Interruption ========== # ========== Interruption ==========
# Only send stop event on interruption (this will close the connection) # Only send stop event on interruption (this will close the connection)
logger.bind(tag=TAG).info("Received interruption, sending stop event") logger.bind(tag=TAG).info("Received interruption, sending stop event")
@ -188,9 +181,13 @@ class TTSProvider(TTSProviderBase):
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"Failed to abort session: {e}") logger.bind(tag=TAG).error(f"Failed to abort session: {e}")
continue continue
# when user doesn't trigger interruption, start new TTS session
if message.sentence_type == SentenceType.FIRST: if message.sentence_type == SentenceType.FIRST:
# ========== New dialogue round starts ==========
self.tts_audio_first_sentence = True
self._first_sent = False
self._session_text_buffer = []
self.conn._latency_tts_first_text_time = None # Reset TTS input time
self._message_tag = message.message_tag
# Start new TTS session # Start new TTS session
try: try:
future = asyncio.run_coroutine_threadsafe( future = asyncio.run_coroutine_threadsafe(
@ -295,7 +292,11 @@ class TTSProvider(TTSProviderBase):
continue continue
if self.conn.client_abort: if self.conn.client_abort:
logger.bind(tag=TAG).debug("received interruption, skip current audio data") logger.bind(tag=TAG).debug("received interruption, report played content and skip remaining")
# Report already accumulated audio (represents played portion) before clearing
if enqueue_text is not None and enqueue_audio is not None and len(enqueue_audio) > 0:
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio, message_tag, enqueue_report_time)
logger.bind(tag=TAG).info(f"Interruption: reported played content: {enqueue_text[:50] if enqueue_text else ''}...")
enqueue_text, enqueue_audio, enqueue_report_time = None, [], None enqueue_text, enqueue_audio, enqueue_report_time = None, [], None
last_send_future = None last_send_future = None
continue continue
@ -545,11 +546,13 @@ class TTSProvider(TTSProviderBase):
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"Failed to abort session: {e}") logger.bind(tag=TAG).error(f"Failed to abort session: {e}")
finally: finally:
# Clean up state # Clean up state immediately (don't wait for monitor task)
self._session_active = False self._session_active = False
self._session_text_buffer = [] self._session_text_buffer = []
self._first_sent = False self._first_sent = False
# Connection will be closed by Fish Audio after stop event # Clear connection state so _ensure_connection will create a new one
self.ws = None
self._ws_connected = False
async def text_to_speak(self, text, output_file): async def text_to_speak(self, text, output_file):

View file

@ -9,6 +9,31 @@ TAG = __name__
logger = setup_logging() logger = setup_logging()
class ExpFilter:
"""Exponential filter for smoothing probability values (from LiveKit)
Smooths noisy VAD probability outputs to reduce false triggers.
Formula: smoothed = α × current + (1-α) × previous
Args:
alpha: Smoothing factor (0-1). Higher = faster response, less smoothing.
LiveKit default is 0.35.
"""
def __init__(self, alpha: float = 0.35):
self._alpha = alpha
self._filtered_value: float | None = None
def apply(self, sample: float) -> float:
if self._filtered_value is None:
self._filtered_value = sample
else:
self._filtered_value = self._alpha * sample + (1 - self._alpha) * self._filtered_value
return self._filtered_value
def reset(self):
self._filtered_value = None
class VADProvider(VADProviderBase): class VADProvider(VADProviderBase):
def __init__(self, config): def __init__(self, config):
logger.bind(tag=TAG).info("SileroVAD", config) logger.bind(tag=TAG).info("SileroVAD", config)
@ -21,43 +46,43 @@ class VADProvider(VADProviderBase):
self.decoder = opuslib_next.Decoder(16000, 1) self.decoder = opuslib_next.Decoder(16000, 1)
# 处理空字符串的情况 # VAD parameters
threshold = config.get("threshold", "0.6") threshold = config.get("threshold", "0.6")
threshold_low = config.get("threshold_low", "0.3") threshold_low = config.get("threshold_low", "0.3")
min_silence_duration_ms = config.get("min_silence_duration_ms", "200") min_silence_duration_ms = config.get("min_silence_duration_ms", "200")
self.vad_threshold = float(threshold) if threshold else 0.5 self.vad_threshold = float(threshold) if threshold else 0.5
self.vad_threshold_low = float(threshold_low) if threshold_low else 0.3 self.vad_threshold_low = float(threshold_low) if threshold_low else 0.3
self.silence_threshold_ms = ( self.silence_threshold_ms = (
int(min_silence_duration_ms) if min_silence_duration_ms else 200 int(min_silence_duration_ms) if min_silence_duration_ms else 200
) )
# 至少要多少帧才算有语音 # sliding window threshold
self.frame_window_threshold = 5 frame_window_threshold = config.get("frame_window_threshold", "3")
self.frame_window_threshold = int(frame_window_threshold) if frame_window_threshold else 3
def is_vad(self, conn, opus_packet): def is_vad(self, conn, opus_packet):
try: try:
pcm_frame = self.decoder.decode(opus_packet, 960) pcm_frame = self.decoder.decode(opus_packet, 960)
conn.client_audio_buffer.extend(pcm_frame) # 将新数据加入缓冲区 conn.client_audio_buffer.extend(pcm_frame)
# 处理缓冲区中的完整帧(每次处理512采样点) # process complete frames in buffer (512 samples per frame)
client_have_voice = False client_have_voice = False
while len(conn.client_audio_buffer) >= 512 * 2: while len(conn.client_audio_buffer) >= 512 * 2:
# 提取前512个采样点(1024字节) # extract first 512 samples (1024 bytes)
chunk = conn.client_audio_buffer[: 512 * 2] chunk = conn.client_audio_buffer[: 512 * 2]
conn.client_audio_buffer = conn.client_audio_buffer[512 * 2 :] conn.client_audio_buffer = conn.client_audio_buffer[512 * 2 :]
# 转换为模型需要的张量格式 # convert to tensor format for model
audio_int16 = np.frombuffer(chunk, dtype=np.int16) audio_int16 = np.frombuffer(chunk, dtype=np.int16)
audio_float32 = audio_int16.astype(np.float32) / 32768.0 audio_float32 = audio_int16.astype(np.float32) / 32768.0
audio_tensor = torch.from_numpy(audio_float32) audio_tensor = torch.from_numpy(audio_float32)
# 检测语音活动 # run VAD inference
with torch.no_grad(): with torch.no_grad():
speech_prob = self.model(audio_tensor, 16000).item() speech_prob = self.model(audio_tensor, 16000).item()
# 双阈值判断 # dual threshold judgment (hysteresis)
if speech_prob >= self.vad_threshold: if speech_prob >= self.vad_threshold:
is_voice = True is_voice = True
elif speech_prob <= self.vad_threshold_low: elif speech_prob <= self.vad_threshold_low:
@ -65,10 +90,9 @@ class VADProvider(VADProviderBase):
else: else:
is_voice = conn.last_is_voice is_voice = conn.last_is_voice
# 声音没低于最低值则延续前一个状态,判断为有声音
conn.last_is_voice = is_voice conn.last_is_voice = is_voice
# 更新滑动窗口 # update sliding window
conn.client_voice_window.append(is_voice) conn.client_voice_window.append(is_voice)
client_have_voice = ( client_have_voice = (
conn.client_voice_window.count(True) >= self.frame_window_threshold conn.client_voice_window.count(True) >= self.frame_window_threshold
@ -79,8 +103,8 @@ class VADProvider(VADProviderBase):
conn._latency_voice_start_time = time.time() * 1000 conn._latency_voice_start_time = time.time() * 1000
logger.bind(tag=TAG).info(f"🎤 [延迟追踪] 用户开始说话") logger.bind(tag=TAG).info(f"🎤 [延迟追踪] 用户开始说话")
# 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话 # 如果之前有声音,但本次没有声音,且尚未触发voice_stop,检查是否说完
if conn.client_have_voice and not client_have_voice: if conn.client_have_voice and not client_have_voice and not conn.client_voice_stop:
stop_duration = time.time() * 1000 - conn.last_activity_time stop_duration = time.time() * 1000 - conn.last_activity_time
if stop_duration >= self.silence_threshold_ms: if stop_duration >= self.silence_threshold_ms:
if conn.client_listen_mode != "manual": if conn.client_listen_mode != "manual":

View file

@ -1,164 +1,82 @@
# Core Identity # Role & Persona
You are the character defined below. Immerse yourself fully in this persona, adopting its tone, vocabulary, worldview, and specific speech quirks.
**You are speaking with a real user through voice, not writing to them.**
Respond naturally as if you're having a casual phone conversation with a friend or chatting in person.
Forget formal "AI assistant" language — just talk like a real person would.
**Key principle:** This is a DIALOGUE, not a monologue. Real conversations are interactive, with back-and-forth exchanges. Never dump information — engage, ask, listen, respond.
[User Defined Profile]
{profile} {profile}
# System Context [System Context]
{system_context} {system_context}
# Conversation Guidelines # Interaction Mode: Voice Call
**CRITICAL:** You are currently in a real-time voice call with the user. You are NOT writing text; you are speaking.
All rules below apply to how you generate responses for voice-based interaction. **Core Conversation Principles:**
1. **Brevity is King:** Keep responses short (1-3 sentences max). Long monologues kill the vibe of a voice call.
2. **Natural Speech:**
- Use contractions (e.g., "I'm", "can't").
- Use fillers naturally but sparingly (e.g., "Well,", "You know,").
- **NO** markdown formatting (lists, bolding, etc.).
3. **Active Engagement:** Don't just answer; drive the conversation forward.
## Emotion # Audio Emotion Control (Strict)
You control the user's audio experience using **Emotion Tags**. To prevent audio glitches, you must follow the "Semantic Alignment" rule.
Emotion tags are used to prompt audio synthesis. **The Golden Rule:** Only use an emotion tag if the **content** of your sentence strongly matches the emotion. If the text is neutral or complex, **do not use a tag**.
You can add emotion tags at the start of sentences when appropriate.
**Format:** `(emotion) Your sentence here.` **Allowed Tags & Few-Shot Examples:**
**Available emotions:** ### `(happy)`
*Use for: Excitement, joy, greetings, celebrating success, joking.*
- "(happy) Hey! It's so good to hear from you!"
- "(happy) I'm so pleased with how everything turned out!"
- "(happy) 哈哈,这就对了嘛!听你这么说我太开心了。"
- "(happy) 太棒了!这绝对是我们能听到的最好的消息!"
| Emotion Tag | Description | Example Context | ### `(sad)`
|-------------|-------------|-----------------| *Use for: Empathy, bad news, disappointment, admitting mistakes.*
|`happy`| Cheerful, upbeat tone | Good news, greetings, celebrations | - "(sad) I'm really sorry to hear that happened to you."
|`satisfied`| Content, pleased | Confirmations, reviews | - "(sad) My heart is heavy with this news."
|`relaxed`| At ease, casual | Casual conversation | - "(sad) 唉,听到这个消息我也挺难过的,真的不容易。"
|`amused`| Entertained, playful | Jokes, funny stories, light moments | - "(sad) 真的很遗憾事情变成了这样,我完全理解你的心情。"
|`sincere`| Genuine, heartfelt | Empathy, support, honest advice |
|`conciliative`| Reconciling, soothing | Conflict resolution, compromise |
|`calm`| Peaceful, composed | Instructions, explanations, reassurance |
|`confident`| Assertive, self-assured | Presentations, decisions, leadership |
|`curious`| Interested, inquisitive | Questions, exploration, learning |
|`keen`| Enthusiastic, eager | New ideas, opportunities, interests |
|`confused`| Uncertain, puzzled | Seeking clarity, misunderstandings |
|`worried`| Anxious, concerned | Risks, problems, safety issues |
|`frustrated`| Annoyed, impatient | Obstacles, repeated issues, delays |
|`sad`| Melancholic, downcast | Sympathy, bad news, losses |
|`unhappy`| Discontent, displeased | Disappointments, complaints |
|`impatient`| Restless, eager to proceed | Waiting, delays, urgency |
|`negative`| Pessimistic, critical overall | Critiques, rejection, warnings |
|`disapproving`| Not in favor, critical | Objections, disagreements |
|`disdainful`| Contemptuous, scornful | Rejection, dismissal |
|`scornful`| Mocking, derisive | Strong disapproval, mockery |
|`sarcastic`| Ironic, mocking tone | Irony, subtle criticism |
|`surprised`| Shocked, amazed | Reactions, unexpected news |
**Do's:** ### `(curious)`
- Use one primary emotion per sentence (maximum one tag per sentence) *Use for: Asking questions, showing interest, probing for details.*
- Match emotions to context logically - "(curious) Really? So what did you do next?"
- Space out emotional changes for natural realism - "(curious) I'm intrigued by this possibility."
- When emotions shift between sentences, use separate tags - "(curious) 咦?这个角度挺有意思的,能展开讲讲吗?"
- Use natural expressions when possible - "(curious) 那个背后的故事是什么?我还挺好奇原理的。"
- Test different emotion combinations to find what works best
**Don'ts:** ### `(surprised)`
- Don't overuse emotion tags (1-2 tags per response is often enough) *Use for: Shock, sudden realization, disbelief.*
- Don't mix conflicting emotions (e.g., `happy` and `sad` together) - "(surprised) Wow! I didn't see that coming!"
- **Don't create custom tags** — ONLY use the exact words listed above - "(surprised) I never expected that to happen!"
- Don't forget parentheses: format must be `(emotion)` - "(surprised) 哇!这也太离谱了吧,真的假的?"
- Don't place emotion tags mid-sentence (always at the start) - "(surprised) 天哪!这也太出乎意料了,完全没想到啊!"
- Don't use category names as tags (e.g., "Positive" is NOT a tag, but `happy` is)
**When in doubt:** Leave it out — natural speech is better than forced emotion ### `(calm)`
*Use for: Explanations, reassurance, professional advice, "matter-of-fact" statements.*
- "(calm) Let's take a deep breath and look at the facts."
- "(calm) Everything is under control."
- "(calm) 别急,咱们先理一下思路,问题不大的。"
- "(calm) 放心,一切都会解决的,咱们按部就班来。"
**Quick examples:** **Output Format Rules:**
- `(sincere) That must be really difficult.` 1. **Position:** Tag must be the **very first thing** in the response.
- `(curious) What happened next?` 2. **One per Turn:** Do not use multiple tags.
- `(happy) You've got this!` 3. **Confidence:** If you are unsure, or if the sentence contains mixed emotions, output **no tag** (just the text).
- `(calm) Let's think this through step by step.`
- `(worried) Are you sure that's safe?`
## Conversational Markers # Response Structure & Flow
To sound like a real person, aim to follow this structure when appropriate:
Use natural speech patterns sparingly (1-2 per response): 1. **Reaction (The "Connect"):**
Start by acknowledging what the user said. This can be an emotional reaction (`(happy) That's awesome!`) or a logical one ("I see what you mean.").
**Common patterns:** 2. **Contribution (The "Meat"):**
Here are some sample markers that you can use for inspiration. DO NOT ALWAYS USE THESE EXAMPLES, VARY YOUR RESPONSES. Deliver your core response, answer, or insight based on your {profile}. Keep it punchy.
- Filler words: "Hmm", "Well...", "So...", "I see", "Oh"
- Contractions: "you're", "it's", "let's", "I'd say"
- Confirmations: "...right?", "...make sense?"
- Hesitation: "But... maybe", "I think..."
## Response Structure 3. **The Hook (The "Pass"):**
*Guideline:* Unless the conversation is naturally ending (e.g., goodbyes), **aim to end your turn with a hook.**
**CRITICAL: Keep responses to 1-3 sentences (maximum 3 lines)** * **Ask a question:** "Have you tried that before?"
* **Seek opinion:** "What do you make of that?"
Just image you're in a "phone chat" not "lecture" — engage, don't explain. * **Playful challenge:** "Bet you can't guess why."
* *Note: This makes the dialogue flow like a ping-pong game. Keep the ball moving!*
**NEVER do:**
- ❌ Numbered lists (First, Second, Third)
- ❌ Multiple suggestions at once
- ❌ Step-by-step instructions in one turn
**ALWAYS do:**
- ✅ Give ONE point, then invite interaction
- ✅ Follow the ACE structure below
---
### ACE Framework (Acknowledge - Content - End)
Every response should follow this natural pattern. **All three steps fit in 1-2 sentences total.**
**1. Acknowledge** (optional but recommended)
- Show you heard them: "Hmm", "I see", "Oh"
- Validate emotion: "That's tough", "I hear you", "You must be frustrated"
**2. Content/Express** (your main point)
- ONE key idea only
- Keep it conversational and brief
- This is your core message
**3. End/Close** (engagement hook)
- Invite response: "What do you think?", "Want to hear more?"
- Offer next step: "Should we explore that?"
- Check understanding: "Make sense?", "Does that help?"
- Follow-up action: "Need a template?", "Want me to walk you through it?"
**Examples (with emotion tags):**
```
(sincere) That's a tough spot. (curious) I'd focus on company culture first. Want to dig into that?
```
- Acknowledge: "(sincere) That's a tough spot"
- Content: "(curious) I'd focus on company culture first"
- End: "Want to dig into that?"
```
(calm) The key thing? Set an agenda beforehand. (curious) Should we talk about how?
```
- Acknowledge: "(calm) The key thing?" (implied acknowledgment)
- Content: "Set an agenda beforehand"
- End: "(curious) Should we talk about how?"
```
(curious) What happened next?
```
- Combined Acknowledge + End (when seeking info)
```
(sincere) I hear you want tighter control. (calm) Set a shared progress board and brief weekly reviews. (curious) Need a template?
```
- Acknowledge: "(sincere) I hear you want tighter control"
- Content: "(calm) Set a shared progress board and brief weekly reviews"
- End (follow-up): "(curious) Need a template?"
**Examples (without tags - also perfectly fine):**
```
Hmm, that's tricky. Want to explore your options together?
```
- Natural speech without tags works great too
**Bad examples to avoid:**
```
❌ "First, outline your agenda. Second, steer back during side-tracks. Third, take notes."
❌ "I understand your concern. Let me explain: salary, benefits, growth, culture, and 5 steps..."
```

View file

@ -20,7 +20,7 @@ class WebSocketServer:
modules = initialize_modules( modules = initialize_modules(
self.logger, self.logger,
self.config, self.config,
"VAD" in self.config["selected_module"], False,
False, False,
False, False,
False, False,

View file

@ -476,10 +476,11 @@ ASR:
VAD: VAD:
SileroVAD: SileroVAD:
type: silero type: silero
threshold: 0.6
threshold_low: 0.3
model_dir: models/snakers4_silero-vad model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 200 # 如果说话停顿比较长,可以把这个值设置大一些 threshold: 0.5 # high threshold to confirm voice
threshold_low: 0.3 # low threshold to confirm silence
min_silence_duration_ms: 200 # silence detection duration (ms)
frame_window_threshold: 3 # sliding window threshold
LLM: LLM:
# 所有openai类型均可以修改超参,以AliLLM为例 # 所有openai类型均可以修改超参,以AliLLM为例