feat: answer calls in the voice channel through the response policy
- conversation.rs: the loop between the core's events and the rest. Finals go through call detection and the response policy; answers are asked of the brain and spoken from the app's queue, an interruption cancels only that answer, a voice stop silences everything, and missed requests are kept without text (last 100). Tested with a fake voice side. - Core: answer(user, text) adopts a playback request the worker speaks under the same id, cancel(id) stops one request, ask_addressed and ask_rank pass the conversation's questions; new SpeakingStopped, Addressed and Ranked events. - Worker client: reply, addressed and rank messages and their results; a reply with no answer, refused or not sent ends its speech as failed. - Voice worker: addressed and rank messages on their own threads, beside a running reply; a spoken reply cancelled while the brain is answering is not spoken. judges.py holds the two short LLM judgements with the heard text fenced as data; eval evals/test_voice_judges.py. - Specs (conversation, discord core, voice worker), docs/llm_contexts.md and the roadmap updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
18
app/tests/fixtures/fake_engine_worker.py
vendored
18
app/tests/fixtures/fake_engine_worker.py
vendored
@@ -1,7 +1,7 @@
|
||||
"""The real voice worker server with fake engines, for the app's protocol tests (no GPU, no models).
|
||||
|
||||
The fake VAD reads speech probability off the amplitude; the fake transcriber names a clip by its
|
||||
pitch ("level 0.9" for a 900 Hz tone); the fake TTS makes 10 samples per character.
|
||||
pitch ("level 0.9" for a 900 Hz tone); the fake TTS makes 10 samples per character; the fake brain answers every reply with two sentences.
|
||||
Run with the repo's src/ on PYTHONPATH: python fake_engine_worker.py <port>
|
||||
"""
|
||||
|
||||
@@ -24,13 +24,27 @@ class LevelTranscriber:
|
||||
return [f"level {np.argmax(np.abs(np.fft.rfft(c))) * 16000 / len(c) / 1000:.1f}" for c in clips]
|
||||
|
||||
|
||||
class FakeBrain:
|
||||
"""Answers with two sentences, says only "켜" (on) requests were said to it, ranks in reverse."""
|
||||
|
||||
def reply(self, user, text, history, chat=None):
|
||||
return "첫 문장입니다. 둘째 문장입니다."
|
||||
|
||||
def addressed(self, user, text, names):
|
||||
return "켜" in text
|
||||
|
||||
def rank(self, candidates):
|
||||
return [c["id"] for c in reversed(candidates)]
|
||||
|
||||
|
||||
class FakeTts:
|
||||
def synthesize(self, text, rate):
|
||||
return np.full(len(text) * 10, 1000, dtype=np.int16)
|
||||
|
||||
|
||||
async def main(port: int) -> None:
|
||||
worker = VoiceWorker(os.environ["JARVIS_VOICE_TOKEN"], LevelTranscriber(), AmplitudeVad, FakeTts())
|
||||
worker = VoiceWorker(os.environ["JARVIS_VOICE_TOKEN"], LevelTranscriber(), AmplitudeVad, FakeTts(),
|
||||
brain=FakeBrain())
|
||||
server = await worker.serve("127.0.0.1", port)
|
||||
print(f"READY 127.0.0.1:{port}", flush=True)
|
||||
await server.serve_forever()
|
||||
|
||||
@@ -286,3 +286,76 @@ async fn chat_channels_go_out_and_chat_actions_come_back_with_their_results() {
|
||||
]);
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_spoken_reply_takes_its_audio_and_a_failed_one_ends_its_speech() {
|
||||
let w = FakeWorker::start(0).await;
|
||||
let (c, mut rx) = client(&w.url(), json!({}));
|
||||
c.start();
|
||||
c.wait_ready(Duration::from_secs(2)).await.expect("ready");
|
||||
assert!(c.reply("r1", 42, "자비스 날씨 어때", true));
|
||||
assert!(c.reply("r2", 43, "자비스 안녕", true));
|
||||
until(|| w.got().len() >= 3).await;
|
||||
assert_eq!(w.got()[1], Got::Json(json!({"type": "reply", "id": "r1", "user": "42", "text": "자비스 날씨 어때",
|
||||
"via": "voice", "speak": true})));
|
||||
// The brain's answer is spoken under the reply id, so its audio reaches the app.
|
||||
w.send(Message::text(json!({"type": "reply_text", "id": "r1", "text": "맑아요.", "failed": false}).to_string()));
|
||||
w.send(tts_frame("r1", 0));
|
||||
let e = next_matching(&mut rx, |e| matches!(e, WorkerEvent::ReplyText { .. })).await;
|
||||
assert_eq!(e, WorkerEvent::ReplyText { id: "r1".into(), text: "맑아요.".into(), failed: false });
|
||||
next_matching(&mut rx, |e| matches!(e, WorkerEvent::TtsAudio { id, .. } if id == "r1")).await;
|
||||
// No answer: nothing will be spoken, so its speech ends as failed.
|
||||
w.send(Message::text(json!({"type": "reply_text", "id": "r2", "text": "", "failed": true}).to_string()));
|
||||
let e = next_matching(&mut rx, |e| matches!(e, WorkerEvent::TtsDone(_))).await;
|
||||
assert_eq!(e, WorkerEvent::TtsDone(TtsDone { id: "r2".into(), chunks: 0, cancelled: false, failed: true }));
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_reply_the_worker_cannot_answer_or_send_ends_as_failed() {
|
||||
let w = FakeWorker::start(0).await;
|
||||
let (c, mut rx) = client(&w.url(), json!({}));
|
||||
c.start();
|
||||
c.wait_ready(Duration::from_secs(2)).await.expect("ready");
|
||||
c.reply("r3", 42, "x", true);
|
||||
w.send(Message::text(json!({"type": "error", "code": "brain_unavailable", "message": "no", "id": "r3"}).to_string()));
|
||||
let e = next_matching(&mut rx, |e| matches!(e, WorkerEvent::TtsDone(_))).await;
|
||||
assert_eq!(e, WorkerEvent::TtsDone(TtsDone { id: "r3".into(), chunks: 0, cancelled: false, failed: true }));
|
||||
c.close();
|
||||
|
||||
let (c, mut rx) = client("ws://127.0.0.1:1", json!({}));
|
||||
assert!(!c.reply("r4", 42, "x", true));
|
||||
let e = next_matching(&mut rx, |_| true).await;
|
||||
assert_eq!(e, WorkerEvent::TtsDone(TtsDone { id: "r4".into(), chunks: 0, cancelled: false, failed: true }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn addressed_and_rank_questions_go_out_and_their_answers_come_back() {
|
||||
let w = FakeWorker::start(0).await;
|
||||
let (c, mut rx) = client(&w.url(), json!({}));
|
||||
c.start();
|
||||
c.wait_ready(Duration::from_secs(2)).await.expect("ready");
|
||||
assert!(c.addressed("q1", 42, "불 좀 꺼 줄래"));
|
||||
assert!(c.rank("k2", &[("7".into(), 42, "날씨".into()), ("8".into(), 43, "불 꺼".into())]));
|
||||
until(|| w.got().len() >= 3).await;
|
||||
let got: Vec<Value> = w.got()[1..].iter().map(|g| match g { Got::Json(v) => v.clone(), Got::Bin(_) => json!(null) }).collect();
|
||||
assert_eq!(got, vec![
|
||||
json!({"type": "addressed", "id": "q1", "user": "42", "text": "불 좀 꺼 줄래"}),
|
||||
json!({"type": "rank", "id": "k2", "candidates": [{"id": "7", "user": "42", "text": "날씨"},
|
||||
{"id": "8", "user": "43", "text": "불 꺼"}]}),
|
||||
]);
|
||||
w.send(Message::text(json!({"type": "addressed_result", "id": "q1", "addressed": true, "failed": false}).to_string()));
|
||||
w.send(Message::text(json!({"type": "rank_result", "id": "k2", "order": ["8", "7"], "failed": false}).to_string()));
|
||||
let e = next_matching(&mut rx, |e| matches!(e, WorkerEvent::Addressed { .. })).await;
|
||||
assert_eq!(e, WorkerEvent::Addressed { id: "q1".into(), addressed: true });
|
||||
let e = next_matching(&mut rx, |e| matches!(e, WorkerEvent::Ranked { .. })).await;
|
||||
assert_eq!(e, WorkerEvent::Ranked { id: "k2".into(), order: vec!["8".into(), "7".into()] });
|
||||
// A failed judgement is a "no", and a failed ranking has no order.
|
||||
w.send(Message::text(json!({"type": "addressed_result", "id": "q3", "addressed": true, "failed": true}).to_string()));
|
||||
w.send(Message::text(json!({"type": "rank_result", "id": "k4", "order": ["8"], "failed": true}).to_string()));
|
||||
let e = next_matching(&mut rx, |e| matches!(e, WorkerEvent::Addressed { .. })).await;
|
||||
assert_eq!(e, WorkerEvent::Addressed { id: "q3".into(), addressed: false });
|
||||
let e = next_matching(&mut rx, |e| matches!(e, WorkerEvent::Ranked { .. })).await;
|
||||
assert_eq!(e, WorkerEvent::Ranked { id: "k4".into(), order: vec![] });
|
||||
c.close();
|
||||
}
|
||||
|
||||
@@ -105,6 +105,46 @@ async fn audio_and_tts_round_trip_through_the_python_server() {
|
||||
.await
|
||||
.expect("speech end");
|
||||
assert_eq!((end.played, end.cancelled, end.failed), (2, false, false));
|
||||
|
||||
// A spoken brain answer plays under the adopted id, like a TTS request.
|
||||
let id = p.adopt();
|
||||
assert!(c.reply(&id, 42, "자비스 안녕", true));
|
||||
let end = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
match rx.recv().await.unwrap() {
|
||||
WorkerEvent::TtsAudio { id, seq, pcm } => {
|
||||
p.audio(&id, seq, pcm);
|
||||
p.clip_ended();
|
||||
}
|
||||
WorkerEvent::TtsDone(d) => p.done(&d),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(PlaybackEvent::End(e)) = p.take_events().into_iter().find(|e| matches!(e, PlaybackEvent::End(_))) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("answer end");
|
||||
assert_eq!((end.id.as_str(), end.played, end.failed), (id.as_str(), 2, false));
|
||||
|
||||
// The two judgements come back under their ids.
|
||||
assert!(c.addressed("q1", 42, "불 켜 줘"));
|
||||
assert!(c.rank("k1", &[("1".into(), 42, "a".into()), ("2".into(), 43, "b".into())]));
|
||||
let (mut addressed, mut ranked) = (None, None);
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while addressed.is_none() || ranked.is_none() {
|
||||
match rx.recv().await.unwrap() {
|
||||
WorkerEvent::Addressed { id, addressed: a } => addressed = Some((id, a)),
|
||||
WorkerEvent::Ranked { id, order } => ranked = Some((id, order)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("judgements");
|
||||
assert_eq!(addressed, Some(("q1".to_string(), true)));
|
||||
assert_eq!(ranked, Some(("k1".to_string(), vec!["2".to_string(), "1".to_string()])));
|
||||
c.close();
|
||||
let _ = child.kill().await;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user