feat(live-voice): configurable and per-start voice instructions (#13375)
Signed-off-by: Tyler Longwell <tlongwell@squareup.com> Co-authored-by: Eva <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -81,12 +81,22 @@ pub struct LiveVoiceInputMessage {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// `base`, then `added` after a blank line when it has any text.
|
||||
pub fn append_instructions(base: &str, added: Option<&str>) -> String {
|
||||
match added.map(str::trim).filter(|added| !added.is_empty()) {
|
||||
Some(added) => format!("{base}\n\n{added}"),
|
||||
None => base.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait LiveVoiceProvider: Send + Sync {
|
||||
/// `instructions` are added after the provider's own for this start only.
|
||||
async fn start(
|
||||
&self,
|
||||
offer: WebRtcOffer,
|
||||
input_messages: Vec<LiveVoiceInputMessage>,
|
||||
instructions: Option<String>,
|
||||
) -> Result<(WebRtcAnswer, Box<dyn ProviderConnection>)>;
|
||||
}
|
||||
|
||||
@@ -101,4 +111,11 @@ mod tests {
|
||||
assert!(WebRtcOffer::new("offer".into()).is_some());
|
||||
assert!(WebRtcAnswer::new("answer".into()).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn added_instructions_follow_the_base_after_a_blank_line() {
|
||||
assert_eq!(append_instructions("base", None), "base");
|
||||
assert_eq!(append_instructions("base", Some(" \n ")), "base");
|
||||
assert_eq!(append_instructions("base", Some(" more\n")), "base\n\nmore");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,8 @@ use crate::{
|
||||
api_client::TlsConfig,
|
||||
live::{LiveSessionEndReason, LiveSessionEvent},
|
||||
live_voice_provider::{
|
||||
DelegationUpdate, DelegationUpdateDelivery, LiveVoiceInputMessage, LiveVoiceProvider,
|
||||
ProviderConnection, ProviderConnectionEvent, WebRtcAnswer, WebRtcOffer,
|
||||
append_instructions, DelegationUpdate, DelegationUpdateDelivery, LiveVoiceInputMessage,
|
||||
LiveVoiceProvider, ProviderConnection, ProviderConnectionEvent, WebRtcAnswer, WebRtcOffer,
|
||||
},
|
||||
openai_live::{
|
||||
ConnectedOpenAiLiveSession, OpenAiLiveClient, OpenAiLiveContext, OpenAiLiveContextChannel,
|
||||
@@ -79,10 +79,11 @@ impl LiveVoiceProvider for OpenAiLiveVoiceProvider {
|
||||
&self,
|
||||
offer: WebRtcOffer,
|
||||
input_messages: Vec<LiveVoiceInputMessage>,
|
||||
instructions: Option<String>,
|
||||
) -> Result<(WebRtcAnswer, Box<dyn ProviderConnection>)> {
|
||||
let config = OpenAiLiveSessionConfig {
|
||||
model: self.model.clone(),
|
||||
instructions: self.instructions.clone(),
|
||||
instructions: append_instructions(&self.instructions, instructions.as_deref()),
|
||||
voice: Some(self.voice.clone()),
|
||||
input_messages: input_messages
|
||||
.into_iter()
|
||||
|
||||
@@ -268,7 +268,7 @@ pub struct LiveVoiceAvailabilityResponse {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Get a diagnostic report for a session.
|
||||
/// Start a live voice interaction for a session.
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema, JsonRpcRequest)]
|
||||
#[request(
|
||||
method = "_goose/unstable/session/live-voice/start",
|
||||
@@ -278,6 +278,10 @@ pub struct LiveVoiceAvailabilityResponse {
|
||||
pub struct LiveVoiceStartRequest {
|
||||
pub session_id: String,
|
||||
pub offer_sdp: String,
|
||||
/// Added after goose's live voice instructions, including any configured
|
||||
/// ones, for this interaction only. Blank text adds nothing.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub instructions: Option<String>,
|
||||
#[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")]
|
||||
pub meta: Option<Meta>,
|
||||
}
|
||||
|
||||
@@ -1353,6 +1353,13 @@
|
||||
"offerSdp": {
|
||||
"type": "string"
|
||||
},
|
||||
"instructions": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"description": "Added after goose's live voice instructions, including any configured\nones, for this interaction only. Blank text adds nothing."
|
||||
},
|
||||
"_meta": {
|
||||
"type": [
|
||||
"object",
|
||||
@@ -1365,7 +1372,7 @@
|
||||
"sessionId",
|
||||
"offerSdp"
|
||||
],
|
||||
"description": "Get a diagnostic report for a session.",
|
||||
"description": "Start a live voice interaction for a session.",
|
||||
"x-side": "agent",
|
||||
"x-method": "_goose/unstable/session/live-voice/start"
|
||||
},
|
||||
|
||||
@@ -76,6 +76,7 @@ impl AcpConnection {
|
||||
let start = self.live_voice.start_interaction(
|
||||
reservation,
|
||||
offer,
|
||||
req.instructions,
|
||||
self.services.session_manager.clone(),
|
||||
transcript_publisher,
|
||||
main_agent,
|
||||
|
||||
@@ -5,6 +5,8 @@ use crate::conversation::message::{Message, MessageContent};
|
||||
use crate::conversation::Conversation;
|
||||
use crate::session::SessionManager;
|
||||
use crate::token_counter::TokenCounter;
|
||||
#[cfg(feature = "live-voice")]
|
||||
use goose_providers::live_voice_provider::append_instructions;
|
||||
use goose_providers::live_voice_provider::{LiveVoiceInputMessage, LiveVoiceProvider};
|
||||
pub(crate) use goose_providers::live_voice_provider::{WebRtcAnswer, WebRtcOffer};
|
||||
#[cfg(feature = "live-voice")]
|
||||
@@ -29,6 +31,8 @@ const LIVE_VOICE_MODEL_CONFIG_KEY: &str = "GOOSE_LIVE_VOICE_MODEL";
|
||||
#[cfg(feature = "live-voice")]
|
||||
const LIVE_VOICE_API_KEY_CONFIG_KEY: &str = "GOOSE_LIVE_VOICE_API_KEY";
|
||||
#[cfg(feature = "live-voice")]
|
||||
const LIVE_VOICE_INSTRUCTIONS_CONFIG_KEY: &str = "GOOSE_LIVE_VOICE_INSTRUCTIONS";
|
||||
#[cfg(feature = "live-voice")]
|
||||
const DEFAULT_OPENAI_LIVE_VOICE: &str = "marin";
|
||||
|
||||
#[cfg(feature = "live-voice")]
|
||||
@@ -270,6 +274,7 @@ impl LiveVoiceService {
|
||||
&self,
|
||||
interaction_guard: LiveVoiceInteractionGuard,
|
||||
offer: WebRtcOffer,
|
||||
instructions: Option<String>,
|
||||
session_manager: Arc<SessionManager>,
|
||||
transcript_publisher: LiveVoiceTranscriptPublisher,
|
||||
main_agent: LiveMainAgent,
|
||||
@@ -287,7 +292,7 @@ impl LiveVoiceService {
|
||||
return Err(LiveVoiceError::Unavailable);
|
||||
}
|
||||
let (answer, provider_connection) = provider
|
||||
.start(offer, input_messages)
|
||||
.start(offer, input_messages, instructions)
|
||||
.await
|
||||
.map_err(|_| LiveVoiceError::StartFailed)?;
|
||||
|
||||
@@ -370,6 +375,7 @@ struct LiveVoiceSettings {
|
||||
endpoint: Option<String>,
|
||||
model: Option<String>,
|
||||
voice: String,
|
||||
instructions: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "live-voice")]
|
||||
@@ -399,11 +405,15 @@ fn live_voice_settings(config: &crate::config::Config) -> Result<LiveVoiceSettin
|
||||
let voice = config
|
||||
.get_param::<String>(LIVE_VOICE_CONFIG_KEY)
|
||||
.unwrap_or_else(|_| DEFAULT_OPENAI_LIVE_VOICE.into());
|
||||
let instructions = config
|
||||
.get_param::<String>(LIVE_VOICE_INSTRUCTIONS_CONFIG_KEY)
|
||||
.ok();
|
||||
Ok(LiveVoiceSettings {
|
||||
api_key,
|
||||
endpoint,
|
||||
model,
|
||||
voice,
|
||||
instructions,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -427,7 +437,8 @@ fn live_voice_provider(
|
||||
let mut provider = OpenAiLiveVoiceProvider::new(
|
||||
settings.api_key,
|
||||
settings.voice,
|
||||
LIVE_SESSION_INSTRUCTIONS.into(),
|
||||
// Added to goose's own instructions, never in place of them.
|
||||
append_instructions(LIVE_SESSION_INSTRUCTIONS, settings.instructions.as_deref()),
|
||||
DELEGATION_DELIVERY_FAILURE_INSTRUCTIONS.into(),
|
||||
)
|
||||
.map_err(|_| "Live voice provider is not configured")?;
|
||||
|
||||
@@ -95,6 +95,7 @@ fn spawn_start(
|
||||
.start_interaction(
|
||||
reservation,
|
||||
WebRtcOffer::new(offer.into()).unwrap(),
|
||||
Some("start instructions".into()),
|
||||
session_manager,
|
||||
ignore_transcript_publisher(),
|
||||
ignore_main_agent(),
|
||||
@@ -148,6 +149,7 @@ async fn establish_interaction_with(
|
||||
.start_interaction(
|
||||
reservation,
|
||||
WebRtcOffer::new("offer".into()).unwrap(),
|
||||
None,
|
||||
start_manager,
|
||||
transcript_publisher,
|
||||
main_agent,
|
||||
@@ -296,6 +298,7 @@ async fn a_start_reserves_the_session_until_it_finishes() {
|
||||
);
|
||||
let pending = starts.recv().await.unwrap();
|
||||
|
||||
assert_eq!(pending.instructions.as_deref(), Some("start instructions"));
|
||||
assert_eq!(
|
||||
pending.input_messages,
|
||||
vec![LiveVoiceInputMessage {
|
||||
@@ -337,6 +340,7 @@ async fn a_cancelled_reservation_does_not_contact_the_provider() {
|
||||
.start_interaction(
|
||||
reservation,
|
||||
WebRtcOffer::new("offer".into()).unwrap(),
|
||||
None,
|
||||
manager,
|
||||
ignore_transcript_publisher(),
|
||||
ignore_main_agent(),
|
||||
@@ -778,6 +782,7 @@ async fn transcript_is_projected_and_flushed_before_delegation() {
|
||||
.start_interaction(
|
||||
reservation,
|
||||
WebRtcOffer::new("offer".into()).unwrap(),
|
||||
None,
|
||||
start_manager,
|
||||
transcript_publisher,
|
||||
main_agent,
|
||||
@@ -1082,6 +1087,7 @@ async fn provider_terminal_publishes_completion_after_release() {
|
||||
.start_interaction(
|
||||
reservation,
|
||||
WebRtcOffer::new("offer".into()).unwrap(),
|
||||
None,
|
||||
manager,
|
||||
ignore_transcript_publisher(),
|
||||
ignore_main_agent(),
|
||||
@@ -1190,7 +1196,7 @@ fn stale_cleanup_cannot_remove_a_later_call() {
|
||||
|
||||
#[cfg(feature = "live-voice")]
|
||||
mod settings {
|
||||
use super::super::{live_voice_provider, live_voice_settings};
|
||||
use super::super::{live_voice_provider, live_voice_settings, LIVE_SESSION_INSTRUCTIONS};
|
||||
use crate::config::Config;
|
||||
use goose_providers::live_voice_provider::{LiveVoiceProvider, WebRtcOffer};
|
||||
use tempfile::TempDir;
|
||||
@@ -1199,12 +1205,13 @@ mod settings {
|
||||
Mock, MockServer, ResponseTemplate,
|
||||
};
|
||||
|
||||
const ENV: [(&str, Option<&str>); 5] = [
|
||||
const ENV: [(&str, Option<&str>); 6] = [
|
||||
("OPENAI_API_KEY", None),
|
||||
("GOOSE_LIVE_VOICE_ENDPOINT", None),
|
||||
("GOOSE_LIVE_VOICE_MODEL", None),
|
||||
("GOOSE_LIVE_VOICE_API_KEY", None),
|
||||
("GOOSE_LIVE_VOICE", None),
|
||||
("GOOSE_LIVE_VOICE_INSTRUCTIONS", None),
|
||||
];
|
||||
const ENDPOINT: &str = "http://192.0.2.10:8080/v1/live/sessions";
|
||||
|
||||
@@ -1238,6 +1245,7 @@ mod settings {
|
||||
assert_eq!(settings.endpoint, None);
|
||||
assert_eq!(settings.model, None);
|
||||
assert_eq!(settings.voice, "marin");
|
||||
assert_eq!(settings.instructions, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1349,7 +1357,7 @@ mod settings {
|
||||
|
||||
let start = live_voice_provider(&config)
|
||||
.unwrap()
|
||||
.start(WebRtcOffer::new("offer-sdp".into()).unwrap(), vec![])
|
||||
.start(WebRtcOffer::new("offer-sdp".into()).unwrap(), vec![], None)
|
||||
.await;
|
||||
|
||||
assert!(start.is_err());
|
||||
@@ -1358,6 +1366,73 @@ mod settings {
|
||||
assert_eq!(body["session"]["model"], "custom-live-model");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn added_instructions_follow_goose_instructions() {
|
||||
let _env = env_lock::lock_env(ENV);
|
||||
for (added, per_start, expected) in [
|
||||
(None, None, LIVE_SESSION_INSTRUCTIONS.to_owned()),
|
||||
(
|
||||
Some(" \n "),
|
||||
Some(" "),
|
||||
LIVE_SESSION_INSTRUCTIONS.to_owned(),
|
||||
),
|
||||
(
|
||||
Some(" You are Billy.\n"),
|
||||
None,
|
||||
format!("{LIVE_SESSION_INSTRUCTIONS}\n\nYou are Billy."),
|
||||
),
|
||||
(
|
||||
None,
|
||||
Some(" Billy likes tea.\n"),
|
||||
format!("{LIVE_SESSION_INSTRUCTIONS}\n\nBilly likes tea."),
|
||||
),
|
||||
(
|
||||
Some("You are Billy."),
|
||||
Some(" Billy likes tea.\n"),
|
||||
format!("{LIVE_SESSION_INSTRUCTIONS}\n\nYou are Billy.\n\nBilly likes tea."),
|
||||
),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.respond_with(ResponseTemplate::new(503))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let directory = TempDir::new().unwrap();
|
||||
let config = config(&directory);
|
||||
config
|
||||
.set_secret("GOOSE_LIVE_VOICE_API_KEY", &"voice-key")
|
||||
.unwrap();
|
||||
config
|
||||
.set_param(
|
||||
"GOOSE_LIVE_VOICE_ENDPOINT",
|
||||
format!("{}/v1/live/sessions", server.uri()),
|
||||
)
|
||||
.unwrap();
|
||||
if let Some(added) = added {
|
||||
config
|
||||
.set_param("GOOSE_LIVE_VOICE_INSTRUCTIONS", added)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let start = live_voice_provider(&config)
|
||||
.unwrap()
|
||||
.start(
|
||||
WebRtcOffer::new("offer-sdp".into()).unwrap(),
|
||||
vec![],
|
||||
per_start.map(String::from),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(start.is_err());
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap();
|
||||
assert_eq!(
|
||||
body["session"]["instructions"], expected,
|
||||
"{added:?} {per_start:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_start_reads_a_key_another_process_saved() {
|
||||
let _env = env_lock::lock_env(ENV);
|
||||
|
||||
@@ -25,11 +25,13 @@ impl LiveVoiceProvider for FakeLiveVoiceProvider {
|
||||
&self,
|
||||
_offer: WebRtcOffer,
|
||||
input_messages: Vec<LiveVoiceInputMessage>,
|
||||
instructions: Option<String>,
|
||||
) -> Result<(WebRtcAnswer, Box<dyn ProviderConnection>)> {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
self.start_tx
|
||||
.send(FakeStartRequest {
|
||||
input_messages,
|
||||
instructions,
|
||||
response_tx,
|
||||
})
|
||||
.map_err(|_| anyhow!("fake provider driver dropped"))?;
|
||||
@@ -41,6 +43,7 @@ impl LiveVoiceProvider for FakeLiveVoiceProvider {
|
||||
|
||||
pub(super) struct FakeStartRequest {
|
||||
pub(super) input_messages: Vec<LiveVoiceInputMessage>,
|
||||
pub(super) instructions: Option<String>,
|
||||
response_tx: oneshot::Sender<Result<(WebRtcAnswer, Box<dyn ProviderConnection>)>>,
|
||||
}
|
||||
|
||||
|
||||
@@ -696,11 +696,16 @@ export type LiveVoiceAvailabilityResponse_unstable = {
|
||||
export type LiveVoiceStatus = 'ready' | 'unavailable';
|
||||
|
||||
/**
|
||||
* Get a diagnostic report for a session.
|
||||
* Start a live voice interaction for a session.
|
||||
*/
|
||||
export type LiveVoiceStartRequest_unstable = {
|
||||
sessionId: string;
|
||||
offerSdp: string;
|
||||
/**
|
||||
* Added after goose's live voice instructions, including any configured
|
||||
* ones, for this interaction only. Blank text adds nothing.
|
||||
*/
|
||||
instructions?: string | null;
|
||||
_meta?: {
|
||||
[key: string]: unknown;
|
||||
} | null;
|
||||
|
||||
@@ -439,11 +439,12 @@ export const zLiveVoiceAvailabilityResponse_unstable = z.object({
|
||||
});
|
||||
|
||||
/**
|
||||
* Get a diagnostic report for a session.
|
||||
* Start a live voice interaction for a session.
|
||||
*/
|
||||
export const zLiveVoiceStartRequest_unstable = z.object({
|
||||
sessionId: z.string(),
|
||||
offerSdp: z.string(),
|
||||
instructions: z.string().nullish(),
|
||||
_meta: z.record(z.string(), z.unknown()).nullish()
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user