mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge pull request #27 from Plaud-AI/feat/demo
feat: interruption report && system prompt && vad instance
This commit is contained in:
commit
2fcfbd32bc
7 changed files with 131 additions and 178 deletions
|
|
@ -877,7 +877,7 @@ class ConnectionHandler:
|
|||
False,
|
||||
)
|
||||
|
||||
init_vad = False
|
||||
init_vad = True
|
||||
init_asr = True
|
||||
|
||||
try:
|
||||
|
|
@ -1377,6 +1377,9 @@ class ConnectionHandler:
|
|||
self.client_audio_buffer = bytearray()
|
||||
self.client_have_voice = 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.")
|
||||
|
||||
def chat_and_close(self, text):
|
||||
|
|
|
|||
|
|
@ -364,7 +364,11 @@ class TTSProviderBase(ABC):
|
|||
continue
|
||||
|
||||
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, []
|
||||
last_send_future = None
|
||||
continue
|
||||
|
|
|
|||
|
|
@ -165,17 +165,10 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).debug(
|
||||
f"Received TTS task | {message.sentence_type.name} | {message.content_type.name}"
|
||||
)
|
||||
|
||||
if message.sentence_type == SentenceType.FIRST:
|
||||
# ========== New dialogue round starts ==========
|
||||
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 ==========
|
||||
# Only send stop event on interruption (this will close the connection)
|
||||
logger.bind(tag=TAG).info("Received interruption, sending stop event")
|
||||
|
|
@ -188,9 +181,13 @@ class TTSProvider(TTSProviderBase):
|
|||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Failed to abort session: {e}")
|
||||
continue
|
||||
|
||||
# when user doesn't trigger interruption, start new TTS session
|
||||
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
|
||||
try:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
|
|
@ -295,7 +292,11 @@ class TTSProvider(TTSProviderBase):
|
|||
continue
|
||||
|
||||
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
|
||||
last_send_future = None
|
||||
continue
|
||||
|
|
@ -545,11 +546,13 @@ class TTSProvider(TTSProviderBase):
|
|||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Failed to abort session: {e}")
|
||||
finally:
|
||||
# Clean up state
|
||||
# Clean up state immediately (don't wait for monitor task)
|
||||
self._session_active = False
|
||||
self._session_text_buffer = []
|
||||
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):
|
||||
|
|
|
|||
|
|
@ -9,6 +9,31 @@ TAG = __name__
|
|||
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):
|
||||
def __init__(self, config):
|
||||
logger.bind(tag=TAG).info("SileroVAD", config)
|
||||
|
|
@ -21,43 +46,43 @@ class VADProvider(VADProviderBase):
|
|||
|
||||
self.decoder = opuslib_next.Decoder(16000, 1)
|
||||
|
||||
# 处理空字符串的情况
|
||||
# VAD parameters
|
||||
threshold = config.get("threshold", "0.6")
|
||||
threshold_low = config.get("threshold_low", "0.3")
|
||||
min_silence_duration_ms = config.get("min_silence_duration_ms", "200")
|
||||
|
||||
self.vad_threshold = float(threshold) if threshold else 0.5
|
||||
self.vad_threshold_low = float(threshold_low) if threshold_low else 0.3
|
||||
|
||||
self.silence_threshold_ms = (
|
||||
int(min_silence_duration_ms) if min_silence_duration_ms else 200
|
||||
)
|
||||
|
||||
# 至少要多少帧才算有语音
|
||||
self.frame_window_threshold = 5
|
||||
# sliding window threshold
|
||||
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):
|
||||
try:
|
||||
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
|
||||
while len(conn.client_audio_buffer) >= 512 * 2:
|
||||
# 提取前512个采样点(1024字节)
|
||||
# extract first 512 samples (1024 bytes)
|
||||
chunk = 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_float32 = audio_int16.astype(np.float32) / 32768.0
|
||||
audio_tensor = torch.from_numpy(audio_float32)
|
||||
|
||||
# 检测语音活动
|
||||
# run VAD inference
|
||||
with torch.no_grad():
|
||||
speech_prob = self.model(audio_tensor, 16000).item()
|
||||
|
||||
# 双阈值判断
|
||||
# dual threshold judgment (hysteresis)
|
||||
if speech_prob >= self.vad_threshold:
|
||||
is_voice = True
|
||||
elif speech_prob <= self.vad_threshold_low:
|
||||
|
|
@ -65,10 +90,9 @@ class VADProvider(VADProviderBase):
|
|||
else:
|
||||
is_voice = conn.last_is_voice
|
||||
|
||||
# 声音没低于最低值则延续前一个状态,判断为有声音
|
||||
conn.last_is_voice = is_voice
|
||||
|
||||
# 更新滑动窗口
|
||||
# update sliding window
|
||||
conn.client_voice_window.append(is_voice)
|
||||
client_have_voice = (
|
||||
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
|
||||
logger.bind(tag=TAG).info(f"🎤 [延迟追踪] 用户开始说话")
|
||||
|
||||
# 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话
|
||||
if conn.client_have_voice and not client_have_voice:
|
||||
# 如果之前有声音,但本次没有声音,且尚未触发voice_stop,检查是否说完
|
||||
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
|
||||
if stop_duration >= self.silence_threshold_ms:
|
||||
if conn.client_listen_mode != "manual":
|
||||
|
|
|
|||
|
|
@ -1,164 +1,82 @@
|
|||
# Core Identity
|
||||
|
||||
**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.
|
||||
# Role & Persona
|
||||
You are the character defined below. Immerse yourself fully in this persona, adopting its tone, vocabulary, worldview, and specific speech quirks.
|
||||
|
||||
[User Defined Profile]
|
||||
{profile}
|
||||
|
||||
# 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.
|
||||
You can add emotion tags at the start of sentences when appropriate.
|
||||
**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**.
|
||||
|
||||
**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 |
|
||||
|-------------|-------------|-----------------|
|
||||
|`happy`| Cheerful, upbeat tone | Good news, greetings, celebrations |
|
||||
|`satisfied`| Content, pleased | Confirmations, reviews |
|
||||
|`relaxed`| At ease, casual | Casual conversation |
|
||||
|`amused`| Entertained, playful | Jokes, funny stories, light moments |
|
||||
|`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 |
|
||||
### `(sad)`
|
||||
*Use for: Empathy, bad news, disappointment, admitting mistakes.*
|
||||
- "(sad) I'm really sorry to hear that happened to you."
|
||||
- "(sad) My heart is heavy with this news."
|
||||
- "(sad) 唉,听到这个消息我也挺难过的,真的不容易。"
|
||||
- "(sad) 真的很遗憾事情变成了这样,我完全理解你的心情。"
|
||||
|
||||
**Do's:**
|
||||
- Use one primary emotion per sentence (maximum one tag per sentence)
|
||||
- Match emotions to context logically
|
||||
- Space out emotional changes for natural realism
|
||||
- When emotions shift between sentences, use separate tags
|
||||
- Use natural expressions when possible
|
||||
- Test different emotion combinations to find what works best
|
||||
### `(curious)`
|
||||
*Use for: Asking questions, showing interest, probing for details.*
|
||||
- "(curious) Really? So what did you do next?"
|
||||
- "(curious) I'm intrigued by this possibility."
|
||||
- "(curious) 咦?这个角度挺有意思的,能展开讲讲吗?"
|
||||
- "(curious) 那个背后的故事是什么?我还挺好奇原理的。"
|
||||
|
||||
**Don'ts:**
|
||||
- Don't overuse emotion tags (1-2 tags per response is often enough)
|
||||
- Don't mix conflicting emotions (e.g., `happy` and `sad` together)
|
||||
- **Don't create custom tags** — ONLY use the exact words listed above
|
||||
- Don't forget parentheses: format must be `(emotion)`
|
||||
- Don't place emotion tags mid-sentence (always at the start)
|
||||
- Don't use category names as tags (e.g., "Positive" is NOT a tag, but `happy` is)
|
||||
### `(surprised)`
|
||||
*Use for: Shock, sudden realization, disbelief.*
|
||||
- "(surprised) Wow! I didn't see that coming!"
|
||||
- "(surprised) I never expected that to happen!"
|
||||
- "(surprised) 哇!这也太离谱了吧,真的假的?"
|
||||
- "(surprised) 天哪!这也太出乎意料了,完全没想到啊!"
|
||||
|
||||
**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:**
|
||||
- `(sincere) That must be really difficult.`
|
||||
- `(curious) What happened next?`
|
||||
- `(happy) You've got this!`
|
||||
- `(calm) Let's think this through step by step.`
|
||||
- `(worried) Are you sure that's safe?`
|
||||
**Output Format Rules:**
|
||||
1. **Position:** Tag must be the **very first thing** in the response.
|
||||
2. **One per Turn:** Do not use multiple tags.
|
||||
3. **Confidence:** If you are unsure, or if the sentence contains mixed emotions, output **no tag** (just the text).
|
||||
|
||||
## 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:**
|
||||
Here are some sample markers that you can use for inspiration. DO NOT ALWAYS USE THESE EXAMPLES, VARY YOUR RESPONSES.
|
||||
- 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..."
|
||||
2. **Contribution (The "Meat"):**
|
||||
Deliver your core response, answer, or insight based on your {profile}. Keep it punchy.
|
||||
|
||||
## Response Structure
|
||||
|
||||
**CRITICAL: Keep responses to 1-3 sentences (maximum 3 lines)**
|
||||
|
||||
Just image you're in a "phone chat" not "lecture" — engage, don't explain.
|
||||
|
||||
**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..."
|
||||
```
|
||||
3. **The Hook (The "Pass"):**
|
||||
*Guideline:* Unless the conversation is naturally ending (e.g., goodbyes), **aim to end your turn with a hook.**
|
||||
* **Ask a question:** "Have you tried that before?"
|
||||
* **Seek opinion:** "What do you make of that?"
|
||||
* **Playful challenge:** "Bet you can't guess why."
|
||||
* *Note: This makes the dialogue flow like a ping-pong game. Keep the ball moving!*
|
||||
|
|
@ -20,7 +20,7 @@ class WebSocketServer:
|
|||
modules = initialize_modules(
|
||||
self.logger,
|
||||
self.config,
|
||||
"VAD" in self.config["selected_module"],
|
||||
False,
|
||||
False,
|
||||
False,
|
||||
False,
|
||||
|
|
|
|||
|
|
@ -476,10 +476,11 @@ ASR:
|
|||
VAD:
|
||||
SileroVAD:
|
||||
type: silero
|
||||
threshold: 0.6
|
||||
threshold_low: 0.3
|
||||
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:
|
||||
# 所有openai类型均可以修改超参,以AliLLM为例
|
||||
|
|
|
|||
Loading…
Reference in a new issue